4

I have a scenario where I need to check if a txt file exists, if it doesn't I need to create it.

Immediately after this, I need to populate the file with some text.

This is what my code looks like:

if (!File.Exists(_filePath))
{
    File.Create(_filePath);
}

using (var streamWriter = File.AppendText(_filePath))
{
    //Write to file
}

I receive an exception (System.IO.IOException) on line 5, only when a new file has to be created. Here is the exception:

The process cannot access the file '**redacted file path**' because it is being used by another process.

I don't want to add something like Thread.Sleep(1000);, as that is an awful solution.

Is there a way to find out when the file is free again, so that I can write to it?

5
  • 1
    Use File.Create(_filePath).Close();. File.Create() returns an open file which won't be closed until it's finalizer runs as a side-effect of garbage collection, unless you close it explicitly. But you shouldn't need to create it separately like that. Commented Mar 26, 2019 at 10:51
  • 2
    Why creating the file? Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist.
    – ZorgoZ
    Commented Mar 26, 2019 at 10:52
  • 1
    You should close the filestream after creation, or write immediately, like in msdn example Commented Mar 26, 2019 at 10:53
  • @PavelAnikhouski The using-statement will close and dispose the streamwriter.
    – Esko
    Commented Mar 26, 2019 at 10:53
  • 2
    File.Create creates a file and opens a stream. Either use that stream with StreamWriter or use File.AppendText without File.Create Commented Mar 26, 2019 at 10:57

3 Answers 3

6

Just use StreamWriter with param append = true. It'll create the file if needed.

using (StreamWriter sw = new StreamWriter(_filePath, true, Encoding.Default))
{
   sw.WriteLine("blablabla");
}
2
  • 2
    Actually, OP can just use the code they already have - File.AppendText() will create the file if it doesn't exist. They just need to remove the File.Create() code and all will be fine. Commented Mar 26, 2019 at 10:56
  • Matthew Watson, Definitely)
    – Lana
    Commented Mar 26, 2019 at 10:59
5

FileCreate method return Filestream which should be closed before using StreamWriter

if (!File.Exists(_filePath))
{
// close fileStream
    File.Create(_filePath).Close();
}

using (var streamWriter = File.AppendText(_filePath))
{
    //Write to file
}
4

You were so close, just remove the first if, the File.AppendText will do the trick for you and create file if not there.

using (var streamWriter = File.AppendText(_filePath))
{
    //write to file
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.