0

So the problem is this I declare the variables and open the stream at the begining of the method:

    int i = 0;
    int FailedToCopyImages = 0;
    int NumberOfCopiedImages = 0;
    int PreviouslyCopiedImages = 0;
    TextWriter tw = new StreamWriter(pathToFile, true);

Then I do some stuff in try-catch-finally block and in the `finally part I have :

finally
            {
                Console.WriteLine(i);
                Console.WriteLine(NumberOfCopiedImages);
                Console.WriteLine(PreviouslyCopiedImages);
                Console.WriteLine(FailedToCopyImages);
                tw.WriteLine(" ");
                tw.WriteLine("All images: " + i +
                    " | Successfully copied: " + NumberOfCopiedImages +
                    " | Previously copied: " + PreviouslyCopiedImages +
                    " | Failed To Copy: " + FailedToCopyImages);
                tw.WriteLine("--------------End Of Material Images-------------");

I do this in four methods and I get the right results there. Here in the Console I see that the variables holds the correct value but in the txt file I get zeroes (0).

Leron
  • 9,546
  • 35
  • 156
  • 257
  • Something else must be going on. Try setting a breakpoint at the line `tw.WriteLine("All images: "...` and see what the values of the local variables are at that point. – C.Evenhuis Apr 11 '13 at 06:35
  • I did - the values are what they should be (non zero) – Leron Apr 11 '13 at 06:40
  • Is it possible the TextWrite to save some cache. I deleted `tw.WriteLine("All images: " + i +..` but I still get it in my txt file. – Leron Apr 11 '13 at 06:43
  • It won't write anything in a file if you don't tell it to. The cache can only delay writing to a file. Rename/delete the file and run again? – C.Evenhuis Apr 11 '13 at 06:44
  • Just did it, good idea but still I get text that I've deleted and clean-rebuild my solution... strange. – Leron Apr 11 '13 at 06:50
  • Sorry, I figured it out. I was using `System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments + "\\PictureStat.txt)` for path and it seems this holds some cache afterall or whatever. But I changed the path and it works OK. As it was before I set it to MyDocuments. – Leron Apr 11 '13 at 06:57

1 Answers1

0

In most cases you need to call tw.Flush() and tw.Close() (or just wrap new StreamWriter(..) in using (...) statement) before seeing results in file.

Even if it seems to start working with other file path (as you commented) - there's no magic (at least in programming) - and it will fail someday without proper Flush / Dispose.

Lanorkin
  • 7,310
  • 2
  • 42
  • 60