[英]How to create a file in WCF service application in windows
我正在研究WCF服务应用程序。 我想在我的一个函数中创建一个文件,所以现在我这样做了。 首先我去目录创建一个文件然后我做读/写。
string path = AppDomain.CurrentDomain.BaseDirectory;
path += "Emp_data\\json_data.json";
StreamReader reader = new StreamReader(path);
StreamWriter writer = new StreamWriter(path);
我知道我这样做的方式不对。 请建议我一个更好的方法,以便如果没有文件和文件夹它将自动创建。
创建文件与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);
在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);
您的问题通常与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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.