Question

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.

Was it helpful?

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

OTHER TIPS

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

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
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top