Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Txt-File and write to it [duplicate]

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?

like image 359
Morris Avatar asked Dec 03 '22 21:12

Morris


1 Answers

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.

like image 124
hadi Avatar answered Dec 16 '22 11:12

hadi