【问题标题】:How to create a file in WCF service application in windows如何在 Windows 的 WCF 服务应用程序中创建文件
【发布时间】:2014-01-09 07:48:36
【问题描述】:

我正在开发 WCF 服务应用程序。我想在我的一个函数中创建一个文件 所以现在这一次我正在这样做。首先我去目录创建一个文件然后我读/写。

string path = AppDomain.CurrentDomain.BaseDirectory;
path += "Emp_data\\json_data.json";
StreamReader reader = new StreamReader(path);
StreamWriter writer = new StreamWriter(path);

我知道我做错了。请建议我一个更好的方法,以便如果没有文件和文件夹它会自动创建。

【问题讨论】:

  • 任何异常/错误信息?此外,您应该使用 Path.Combine 而不是 "+="
  • 我不与路径混淆。我想创建一个文件,而 StreamReader/ StreamWriter 无法做到这一点。我很确定我的路径。
  • 再次 - 任何异常/错误消息?
  • FileNotFoundException 请给我一种在 WCF SERVICES 中创建文件的方法。我是新手。

标签: c# wcf wcf-rest


【解决方案1】:

您的问题通常与 WCF 服务无关。

这样的事情会起作用(如果你对文件有写权限):

String dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
  Directory.CreateDirectory(dir)

using (FileStream fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
  // work with fs to read from and/or write to file, maybe this
  using (StreamReader reader = new StreamReader(fs))
  {
    using (StreamWriter writer = new StreamWriter(fs))
    {
       // need to sync read and write somehow
    }
  }
}

【讨论】:

  • 这取决于您的应用程序逻辑。通常你会按顺序进行。
【解决方案2】:

创建文件与 WCF 无关。无论上下文如何,这样做都是一样的。我更喜欢使用静态 File 类的方法。

创建文件很简单。

string path = AppDomain.CurrentDomain.BaseDirectory;
path += "Emp_data\\json_data.json";
using(FileStream fs = System.IO.File.Create(path))
{
}

如果你只是想写数据,你可以这样做......

File.WriteAllText(path, contentsIWantToWrite);

【讨论】:

    【解决方案3】:

    在 WCF 中创建文件不会发生任何额外的事情,因此您可以这样做

    string path = AppDomain.CurrentDomain.BaseDirectory;
    String dir = Path.GetDirectoryName(path);
    dir += "\\Emp_data";
    string filename = dir+"\\Json_data.json";
    if (!Directory.Exists(dir))
        Directory.CreateDirectory(dir); // inside the if statement
    FileStream fs = File.Open(filename,FileMode.OpenOrCreate, FileAccess.ReadWrite);
    StreamReader reader = new StreamReader(fs);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      相关资源
      最近更新 更多