Search code examples
c#file-writing

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();

Solution

  • 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();