none
Inconsistencies in Code Execution - Visual Studio 2013

    Question

  • I have been having some problems lately with VS2013. At one time a code executes without errors, and then throws an error the next. The last case I  had was with this code:

    fFile = fFolder + "\\test.txt";               

    if (!File.Exists(fFile)) { File.Create(fFile); }

    sWrite = new StreamWriter(fFile, false, Encoding.Default);               

    sWrite.WriteLine(mainDir + "\r\n Started test " + DateTime.Now); //sWrite.WriteLine("\r\n");                

    sWrite.AutoFlush = true; sWrite.Close();


    At one time this code worked. The file was created, and the text written.

    I made a few adjustments, but then restored the code to the above. Now it throws an IOException, all the time, on this line:

    sWrite = new StreamWriter(fFile, false, Encoding.Default);

    I'm wondering if something on my system is interfering with VS, since I have had a similar problem on other occasions.


    • Edited by JohnG1000 Wednesday, March 16, 2016 11:15 PM ... should be fFile - corrected
    Wednesday, March 16, 2016 4:25 PM

Answers

All replies

  • Does it work better in this case:

        if( ! File.Exists( fFile ) ) File.Create( fFile ).Dispose();

    But this is just an intermediate remedy.

    Wednesday, March 16, 2016 5:48 PM
  • Thanks! That solved the problem.

    I realize that 'Dispose' releases all resources used by System.IO.Stream.

    That would mean that even after the file was created, it did not immediately release the IO stream, hence the text could not be written.

    Could you please explain why this happens, because the code worked on other occasions. Is it a case of memory lag or usage on my system?

    Wednesday, March 16, 2016 11:31 PM
  • If you do not close the stream created with Create, then it will be closed automatically by the System and Garbage Collector, however this will be done at some unpredictable moment, depending on various factors. Probably it will be disposed earlier in environments with less available resources. When the stream remains open, the next file operations on the same file fail. Calling Dispose or Close explicitly, or applying using statement, ensures that the file is unlocked.

    Though it is possible to access the same file from multiple places using the corresponding constructors that take FileShare value.

    Since StreamWriter creates the file that does not exist, then File.Create is not needed.

    Thursday, March 17, 2016 5:58 AM