-1

I have a C# script that creates a file and I would like to update it to add some text to the file.

This is the code that works perfectly to create the file:

String filepath = "";
filepath = "This/is/a/dynamic/file/path.txt";

System.IO.File.Create(filepath);

I would like to add some code to add a line of text to the file. Below is what I have tried, but when I run it I get this error:

error: the process cannot access the file 'This/is/a/dynamic/file/path.txt' because it is being used by another process.

String filepath = "";
filepath = "This/is/a/dynamic/file/path.txt";

System.IO.File.Create(filepath);

System.IO.File.AppendAllText(filepath, "Text to add to file" + Environment.NewLine);

Any help would be much appreciated, and forgive me if this is a dumb question as I'm very new to C#.

Ben Kisow
  • 36
  • 6
  • You need to close file after you create it – Vasya Jun 08 '23 at 20:30
  • 1
    Change this, `System.IO.File.Create(filepath);`, to this, `System.IO.File.Create(filepath).Close();`. The file is still in use by the Create call, you have to ensure you close it before you attempt to access the file again. You don't need to call Close after the AppendAllText as that method will automatically close the file after it appends the text. That said this is fine for quick-and-dirty work but for properly working with files you should review the [MS File info](https://learn.microsoft.com/en-us/dotnet/api/system.io.file?view=net-7.0) – quaabaam Jun 08 '23 at 20:31
  • Does this answer your question? ["System.IO.IOException: The process cannot access the file 'C:\Test\test.txt' because it is being used by another process"](https://stackoverflow.com/questions/54894922/system-io-ioexception-the-process-cannot-access-the-file-c-test-test-txt-be) – Filburt Jun 08 '23 at 20:41

3 Answers3

0

When you use File.Create it returns a FileStream which is IDisposable, you should always use a using statement to ensure it is disposed. This will ensure it releases the file.

using FileStream file = File.Create(filepath);

However, File.AppendAllText will create the file if it doesn't exist and does not return a Stream and it closes the file when done, so no need to worry, just remove the create line all together.

https://learn.microsoft.com/en-us/dotnet/api/system.io.file.appendalltext?view=net-7.0

Tarazed
  • 1,707
  • 1
  • 7
  • 22
0

As mentioned yearlier you missed .Close() immediately after file creation.

Instead I suggest using StreamWriter that will create if doesn't exists, or write into existing file. It also support append or override modes

using (StreamWriter outputFile = new StreamWriter("This/is/a/dynamic/file/path.txt", true)))
{
   outputFile.WriteLine("Text to add to file");
}
Adalyat Nazirov
  • 1,611
  • 2
  • 14
  • 28
0

Your file is still being used (or kept open) by the File.Create() method. So you need to close it after creating the file.

File.Create(filepath).Close();
File.AppendAllText(filepath, "Your text\n");