-3

Hi I tried create and write a text file in C# but I get this error.

The process is being used by another process 'D:\SampleFolder\Sample.txt' can not access the file.

public void WriteToLog(string ClassName, string Message)
{
    string path = @"D:\SampleFolder\" + ClassName + ".txt";

    if (!File.Exists(path))
    {
        File.Create(path);
        TextWriter tw = new StreamWriter(path,true);
        tw.WriteLine(DateTime.Now.ToString() + " " + "Class:" + " " + ClassName + " " + "Message:" + Message);
        tw.Close();
    }

    else if (File.Exists(path))
    {
        TextWriter tw = new StreamWriter(path, true);
        tw.WriteLine(DateTime.Now.ToString() + " " + "Class:" + " " + ClassName + " " + "Message:" + Message);
        tw.Close();
    }
}

..
..
try
{

}
catch (Exception ex)
{       
    WriteToLog(this.GetType().Name, ex.Message);
}
Akshay Soam
  • 1,580
  • 3
  • 21
  • 39
Mhmt
  • 759
  • 3
  • 22
  • 45

1 Answers1

3

You are issuing a File.Create before creating a TextWriter.

File.Create(path);
TextWriter tw = new StreamWriter(path,true);

File.Create by default creates a file and leaves it locked, so your TextWriter can't access to it.

From the documentation:

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

File.Create returns a stream, so either use that stream to write to the file (instead of passing the path to the TextWriter), or just don't call File.Create at all, and let the StreamWriter create the file.

Jcl
  • 27,696
  • 5
  • 61
  • 92
  • 3
    Also use `using` statement. Also, for logging, use existing libraries. – Dialecticus Jan 23 '15 at 16:30
  • @Dialecticus agree on `using`. Don't necessarily on using existing libraries for logging. I was just answering the question as of why the file was locked so that the OP can learn what the problem was: I'd not use the method he uses to write a single line of text to a file anyway :-) – Jcl Jan 23 '15 at 16:32