user15639306
user15639306

Reputation:

Write in new text file after being created

I want to write in the created text file from content in a textbox after it's been created in the app folder.

I'm getting an error saying that it can't write to it because another process is in use, how can I get around this?

I want the content from textbox3 to be written in the newly made file after it's been created. So the text file isn't there, it's making a text file from the user input on textBox2. I want the input from textBox3 to write in the new file right after it's been made.

Error: `System.IO.IOException: 'The process cannot access the file 'C:\Users\Jason\Desktop\app\x.txt' because it is being used by another process.'

Here's my code below:

private void button1_Click(object sender, EventArgs e)
{
    Console.WriteLine();
    Console.WriteLine("GetFolderPath: {0}",
        Environment.GetFolderPath(Environment.SpecialFolder.System));

    string filename = @"C:\Users\Jason\Desktop\app\" + textBox2.Text + ".txt";
    File.Create(filename);
    File.WriteAllText(filename, textBox3.Text);
}

Upvotes: 1

Views: 342

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502816

File.Create returns a FileStream, which will be open until it's disposed.

So you could just dispose of the returned value... but it would be simpler to remove the File.Create call entirely. If the file doesn't exist beforehand, it will be created by the File.WriteAllText call anyway.

Upvotes: 4

Related Questions