问题
I'm working on WCF services application. I want to create a file in one of my function so now this time I'm doing like this. First I go to directory creates a file then i do read/write.
string path = AppDomain.CurrentDomain.BaseDirectory;
path += "Emp_data\\json_data.json";
StreamReader reader = new StreamReader(path);
StreamWriter writer = new StreamWriter(path);
I know I'm doing this in wrong way. Please suggest me a better way so that if there in no file and folder It will create automatically.
回答1:
Nothing extra happens with creating a file in WCF so you can do that like this
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);
回答2:
Creating a file has nothing to do with WCF. Doing so is the same regardless of the context. I prefer to use the methods on the static File class.
To create a file is simple.
string path = AppDomain.CurrentDomain.BaseDirectory;
path += "Emp_data\\json_data.json";
using(FileStream fs = System.IO.File.Create(path))
{
}
If you just want to write data, you can do...
File.WriteAllText(path, contentsIWantToWrite);
回答3:
Your problem is not related to WCF services in general.
Something like this will work (if you have write access to the file):
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
}
}
}
来源:https://stackoverflow.com/questions/20703786/how-to-create-a-file-in-wcf-service-application-in-windows