-2

I needed to log the value of a int (camera tracking application). And so i wrote the following function, tried some variation but so far it only logs 1 data sample, while another command in my main app that refreshes a label does frequently update, why wont this work. The following is part of a dll i wrote with all graphic functions. I did complete recompile etc but it doesn't want to dump my int's in a log :(

public static void DumpIntToFile(string filename, int i)
{
    StreamWriter sw = System.IO.File.AppendText(filename);
    sw.WriteLine(i.ToString());
    sw.Close(); // to commit
}

here the label updates but my log doesnt grow

lblMinimumSurfaceSize.Text = Lijst[i].SurfaceSize.ToString();
MagicMath.DumpIntToFile(@"D:\SampleData.txt", Lijst[i].SurfaceSize);
MethodMan
  • 18,625
  • 6
  • 34
  • 52
Peter
  • 2,043
  • 1
  • 21
  • 45
  • Is it one data sample _each time_ you run the application, or just one sample ever? – CodingGorilla Mar 31 '16 at 15:07
  • Just tried your code, it works fine for me... perhaps you're overwriting the file somewhere else? – Thomas Levesque Mar 31 '16 at 15:08
  • to commit the writing of the line try adding `sw.Flush();` before the `sw.Close();` also you need to look at the overloads there should be a boolean flag that you can set to `true` or `false` in regards to overwriting the existing file or creating a new file. – MethodMan Mar 31 '16 at 15:13
  • @MethodMan he uses AppendText() and Close(), I tried it and this code works. Does it get called multiple times though? – HasaniH Mar 31 '16 at 15:20
  • this is the job of the OP to set up some breakpoints and step through the code.. if the code that's posted works then the issue must be somewhere else in the application. `Use the Debugger` – MethodMan Mar 31 '16 at 15:24
  • Without changing code, but by saving and restarting and recompiling again it worked. i dont know why it didnt work, maybe antivirus file lock ? i got no clue the code was fine. I still marked the flushing as answer since some questions in this direction. As some write apps close it and the stream has not been writen. sw.close should cause flush too, i remind a friend to have once a project where all code was fine but didnt write some xml, some bug about .net didnt flush either, in some cases. – Peter Apr 01 '16 at 12:58

1 Answers1

1

You have to flush your writer:

sw.Flush();
Nikolay Fedorov
  • 387
  • 2
  • 7
  • The call to Close() flushes the buffer – HasaniH Mar 31 '16 at 15:19
  • the call to `Flush()` immediately write it to the file as well so this answer is also valid.. it should not be down voted..! – MethodMan Mar 31 '16 at 15:21
  • Actually while i not used it i like your answer, my code enventually worked for unknown reasons, i think vs2015 had a hard time or so, i didnt alter my code. just tried to compile it again and again (i couldnt see any bug or reason my code shouldnt work) – Peter Apr 01 '16 at 12:52