Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File creates but cannot write in it

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();
        }
    }
like image 704
Smith Avatar asked Nov 28 '22 09:11

Smith


2 Answers

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.

like image 103
Jeroen van Langen Avatar answered Dec 09 '22 14:12

Jeroen van Langen


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.

like image 28
chris.house.00 Avatar answered Dec 09 '22 14:12

chris.house.00