1

I don't understand why the output file does not contain any text? Why is the array not writing to file? I receive no error whilst running it..

    Console.Write("Please enter a name for the homework: ");
    hmwk[1].name = Console.ReadLine();
    Console.Write("Please enter the subject: ");
    hmwk[1].type = Console.ReadLine();

redo:
    Console.Write("Please enter the date the homework was set xx/xx/xx: ");
    string toconvert = Console.ReadLine();
    DateTime temp;
    if (DateTime.TryParse(toconvert, out temp)== false)
    {
        goto redo;
    }

    DateTime converted = DateTime.Parse(toconvert);
    hmwk[1].dateset = converted;

redo2:
    Console.Write("Please enter the date the homework deadline is: ");
    toconvert = Console.ReadLine();
    if (DateTime.TryParse(toconvert, out temp) == false)
    {
        goto redo2;
    }
    converted = DateTime.Parse(toconvert);
    hmwk[1].deadline = converted;
    StreamWriter outfile = new StreamWriter("homework.txt", false);
    outfile.WriteLine(hmwk[1].name);
    outfile.WriteLine(hmwk[1].type);
    outfile.WriteLine(hmwk[1].dateset);
    outfile.WriteLine(hmwk[1].deadline);

    Console.WriteLine("You have added the homework. Press Enter.");
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Ladon
  • 25
  • 2
  • Linked [duplicate](http://stackoverflow.com/questions/7569904/easiest-way-to-read-from-and-write-to-files) shows proper ways to write to file and links to more information on MSDN. As Ksv3n pointed out you are missing `using`. Please also check out http://stackoverflow.com/questions/18671774/c-sharp-allow-user-to-input-again-until-correct as using `goto` is generally frowned upon. – Alexei Levenkov Nov 25 '15 at 17:15
  • Thanks, I'll check out that link, I've heard it is "bad practice" but I have no idea why. – Ladon Nov 25 '15 at 17:34
  • https://www.bing.com/search?q=c%23+why+goto+bad+practce – Alexei Levenkov Nov 25 '15 at 18:28

1 Answers1

4

It's probably because it's not flushed. You should Dispose() StreamWriter so it will automatically flush the buffered data to the file. Dispose example with using:

using (StreamWriter outfile = new StreamWriter("homework.txt", false)) 
{
    outfile.WriteLine(hmwk[1].name);
    outfile.WriteLine(hmwk[1].type);
    outfile.WriteLine(hmwk[1].dateset);
    outfile.WriteLine(hmwk[1].deadline);
}
Perfect28
  • 11,089
  • 3
  • 25
  • 45