When exploring options for creating text files I stumbled across this behavior I cant explain
Both buttons will create a file
but when I create a file with button1 button2 generates an error.
This only occurs when the file is actually created.
After a file is created buttons 1 and two operate as expected
Sample code for a simple GUI program 2 buttons and a multilne text box enclosed
string logFile;
public Form1()
{
InitializeComponent();
logFile = "test.txt";
}
private void button1_Click(object sender, EventArgs e)
{
if (!System.IO.File.Exists(logFile))
{
System.IO.File.Create(logFile);
textBox1.AppendText("File Created\r\n");
}
else
{
textBox1.AppendText("File Already Exists\r\n");
}
System.IO.File.AppendText("aaa");
}
private void button2_Click(object sender, EventArgs e)
{
// 7 overloads for creation of the Stream Writer
bool appendtofile = true;
System.IO.StreamWriter sw;
try
{
sw = new System.IO.StreamWriter(logFile, appendtofile, System.Text.Encoding.ASCII);
sw.WriteLine("test");
textBox1.AppendText("Added To File Created if Needed\r\n");
sw.Close();
}
catch (Exception ex)
{
textBox1.AppendText("Failed to Create or Add\r\n");
// note this happens if button 1 is pushed creating the file
// before button 2 is pushed
// eventually this appears to resolve itself
textBox1.AppendText("\r\n");
textBox1.AppendText(ex.ToString());
textBox1.AppendText("\r\n");
textBox1.AppendText(ex.Message);
}
}
You might be getting an error because file resource is in use by the previous process. While using resources like file (and using a StreamWriter object, which is IDisposable), it is advised to use the "Using" directive. This will close the resource once code execution completes.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
Once you write the third line, file will automatically be closed and resources disposed.