Creating a Txt-File and write to it

31,423

Solution 1

You don't actually have to check if the file exists, as StreamWriter will do that for you.

using (var tw = new StreamWriter(path, true))
{
    tw.WriteLine(TextBox1.Text);
}

public StreamWriter( string path, bool append )

Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.

Solution 2

You should use File.Create with using statement as it's locking the file on creating.So just change this line :

File.Create(path);

To this:

using (File.Create(path));
Share:
31,423
Morris
Author by

Morris

Updated on July 24, 2020

Comments

  • Morris
    Morris almost 4 years

    I want to create a text file then add the text of a TextBox to it. Creating the text file works without any problems with following code:

    InitializeComponent();
    string path = @"C:\Users\Morris\Desktop\test.txt";
    if (!File.Exists(path))
    {
        File.Create(path);
    }
    

    But I get an error that the file is being used when I try to add the text to the text file. If the file already exist before it run the code I don't get this error and the TextBox.Text is added to the File. I use this code to add the text to the text file:

    public void writeTxt()
    {
        string path = @"C:\Users\Morris\Desktop\test.txt";
        if (File.Exists(path))
        {
            using (var tw = new StreamWriter(path, true))
            {
                tw.WriteLine(TextBox1.Text);
                tw.Close();
            }
        }
    }
    

    Can you help me?