Search code examples
c#wcfwcf-rest

How to create a file in WCF service application in windows


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.


Solution

  • 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);