简体   繁体   中英

Unable to write to my text file in C#

The following code does not write to a text file. Unsure as to why, as I am following my book exactly, to my knowledge. No errors are thrown at run-time, the program runs successfully. The file path is correct and the file mentioned is not currently open

String databasePath = "C:\\Users\\Dalton.Riera\\Downloads\\Summer Program Practice 0 Solution Extr\\Summer Program Practice 0 Solution\\DataBase.txt";
StreamWriter Writer = new StreamWriter(new FileStream(databasePath, 
    FileMode.Append, FileAccess.Write));
Writer.WriteLine("Test");
Console.ReadKey();
Writer.Close();

If you want to append, just AppendAllText :

   string databasePath = "C:\\Users\\Dalton.Riera\\Downloads\\Summer Program Practice 0 Solution Extr\\Summer Program Practice 0 Solution\\DataBase.txt";

   File.AppendAllText(databasePath, "Test");

In case you insist on Writer close it before Console.ReadKey (when you check the file)

// first write into the file
//DONE: do not close IDisposable explicitly, but wrap them into "using"
using (StreamWriter Writer = new StreamWriter(
  new FileStream(databasePath, 
                 FileMode.Append, 
                 FileAccess.Write))) {
  Writer.WriteLine("Test");
} 

// ... then stop and check file's content
Console.ReadKey();
Console.ReadKey();
Writer.Close();

Please move the line Console.ReadKey(); after Writer.Close(); . The function ReadKey holds the execution and content is not written to file unless Write.Close function is called. So your code should look like:

String databasePath = "C:\\Users\\Dalton.Riera\\Downloads\\Summer Program Practice 0 Solution Extr\\Summer Program Practice 0 Solution\\DataBase.txt";
StreamWriter Writer = new StreamWriter(new FileStream(databasePath,
FileMode.Append, FileAccess.Write));
Writer.WriteLine("Test");

Writer.Close();
Console.ReadKey();

Whilst your code should work as written, there could be a caching issue:

I'd suggest adding writer.Flush() before your writer.Close() .

On top of this, you should probably be using the StreamWriter not just creating it to ensure that it is correctly disposed of.

Combining these two points would render the following code:

    String databasePath = "C:\\Users\\Dalton.Riera\\Downloads\\Summer Program Practice 0 Solution Extr\\Summer Program Practice 0 Solution\\DataBase.txt";
    using (StreamWriter writer = new StreamWriter(new FileStream(databasePath, 
        FileMode.Append, FileAccess.Write)))
    {
        writer.WriteLine("Test");
        Console.ReadKey();
        writer.Flush();
        //writer.Close(); this may or may not be needed.
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM