My Program: Check for Settings.txt file. If the file is not present, create the text and write into it automatically. If Settings.txt file is already present, ignore. Do not create or write in the existing file.
My Problem: When file is not present, Settings.txt file creates but it is empty. I want the program to write in it when it creates the file. Thanks for your help.
private void Form1_Load(object sender, EventArgs e)
{
string path = @"C:\Users\Smith\Documents\Visual Studio 2010\Projects\Ver.2\Settings.txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine("Manual Numbers=");
tw.WriteLine("");
tw.WriteLine("Installation Technical Manual: ");
tw.WriteLine("Performance Manual: ");
tw.WriteLine("Planned Maintenance Technical Manual: ");
tw.WriteLine("Service Calibration Manual: ");
tw.WriteLine("System Information Manual: ");
tw.WriteLine("");
tw.Close();
}
}
Try this:
using(FileStream stream = File.Create(path))
{
TextWriter tw = new StreamWriter(stream);
tw.WriteLine("Manual Numbers=");
tw.WriteLine("");
tw.WriteLine("Installation Technical Manual: ");
tw.WriteLine("Performance Manual: ");
tw.WriteLine("Planned Maintenance Technical Manual: ");
tw.WriteLine("Service Calibration Manual: ");
tw.WriteLine("System Information Manual: ");
tw.WriteLine("");
}
The using ensures that the filestream is closed(disposed) even when an exception occurs within writing.
The problem is that File.Create returns a FileStream so it leaves the file open. You need to use that FileStream with your TextWriter. You'll also want to wrp the FileStream in a using(...) statement or manually call Dispose() on the FileStream so you ensure the file is closed when you're done processing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With