1

Possible Duplicate:
File being used by another process after using File.Create()

I have a method that will append text to a file. Before I append the text I check if the file exists. If it does not exist I create it then carry on as shown below.

if(!File.Exists(_someFile))
    File.Create(_someFile);

using (StreamWriter file = File.AppendText(_someFile))
{          
    file.WriteLine("some text");
}

If the file exists there is no problem. The file will be updated. If the file does not exist and it gets created an IO exception is thrown on the line with the 'using', stating that another process is using the file. I tried to use process explorer to find out what is using the file and the result is "non existent process". Does anyone know what is happening and how to solve this problem?

EDIT: Problem solved

I could not find a question about my problem on this site when I first searched. As soon as I posted my question I saw the exact problem being address in the 'related questions' on the right. Link to the solution: File being used by another process after using File.Create() Sorry for posting a duplicate. My problem is solved.

Community
  • 1
  • 1
Joseph Devlin
  • 1,754
  • 1
  • 26
  • 37

2 Answers2

7

This happens because File.Create(_someFile); opens the file stream which must be closed before you can use the new created file. Try this:

if(!File.Exists(_someFile))
{
    using (var stream = File.Create(_someFile))
}
using (StreamWriter file = File.AppendText(_someFile))
{          
    file.WriteLine("some text");
}

But actually you don't need to check and create the file first. StreamWriter will create the file if it does't exist or append the text to it if it does exist.

using (StreamWriter sw = new StreamWriter(_someFile, true))
{
    file.WriteLine("some text");
}
VladL
  • 12,769
  • 10
  • 63
  • 83
1

Vlad's answer is correct. Since you want to create the file if it doesn't exist and append to it if it exists, here is simple solution:

        string _someFile = @"C:\somefile.txt";
        TextWriter tw = new StreamWriter(_someFile, true); // append == true
        tw.WriteLine("some text");
        tw.Close();
Uphill_ What '1
  • 683
  • 6
  • 15