Search code examples
c#ssisio

C# - How to create a text file and add a line of text to it?


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#.


Solution

  • 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");
    }