0

I am writing a text file in Appdata folder, I am creating a folder and creating a text file and in next line I am writing text into the file through StreamWriter. But here I am getting following exception.

The process cannot access the file 'C:\sdfdfg\sdfsd\AppData\Roaming\MyFolder\myFile.txt' because it is being used by another process.

This exception I am getting when I create file, if I run app second time than the app is writing the text into same file.

My Code is following

StringBuilder sb=new StringBuilder();
if (!File.Exists(filePath))
{
     File.Create(filePath);
     sb.AppendLine(line);
     using (StreamWriter writer = new StreamWriter(filePath, true))
     {
         writer.Write(sb.ToString());
         writer.Close();
     }
}

I tried another function of File, File.WriteAllText(filePath, textToWrite); but it is also performing same way as above StreamWriter is behaving.

user229044
  • 232,980
  • 40
  • 330
  • 338
Ashish-BeJovial
  • 1,829
  • 3
  • 38
  • 62

1 Answers1

2

The simplest solution is to just leave out File.Create().

The constructor you're using for your StreamWriter will already create the file if it doesn't exist.

Another option is to pass the FileStream that File.Create() returns into an appropriate constructor of StreamWriter.

Willem van Rumpt
  • 6,490
  • 2
  • 32
  • 44
  • Thank you now i have removed the File.Create(filePath); StreamWriter will write the file., such a silly mistake i did.... :(, anyway thank you Willem van Rumpt. cheers! – Ashish-BeJovial Dec 05 '14 at 07:54