none
Bug in .net FX2.0: FileStream, SteamReader, StreamWriter RRS feed

  • Question

  • To reproduce the bug, create a class with a method including such actions:
    1. create a file, and write to it with StreamWriter
    2. close the StreamWriter
    3. call a command line tool to change the file (I used HtmlTidy with -m option which means modify the input file directly) with System.Diagnostics.Process
    4. read the file with StreamReader

    run it, and the result you get is what you've wrote to that file, but not the current file content.

    I used UltraEdit to get notification when the file is modified, and the file does be modified before StreamReader.ReadToEnd().

    workaround: before call StreamReader.ReadToEnd(), call Thread.Sleep(xxx), xxx=100 was ok for me, but I'm not sure if you will get the same result.

    by the way, is there any other tools like htmltidy to clean html code into xhtml 1.0 strict compliant? Can SgmlReader do this stuff?
    Thursday, May 25, 2006 9:01 AM

Answers

  • This is not a bug (or even a feature... :) This is a logic problem. You are not allocating enough time for the external process to finish writing and flushing its buffers to disk. Here is a better way to handle this case:

    using System;
    using System.IO;
    using System.Diagnostics;
    using System.Threading;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
            //Constants
            const string FILENAME = @"C:\Temp\TestData.txt";
            const string PROCESS = @"C:\Temp\DoStuff.cmd";
            const string PARAMS = "";
            const string ORIGINAL_TEXT = "Some Stuff Goes Here.";

            StreamWriter writer = null; //Writer instance.
            StreamReader reader = null; //Reader instance.
            Process externalProcess = null; //External text modifying process.
            string newContent = null; //New content.

            //Write the original file content.
            writer = new StreamWriter(FILENAME);
            writer.WriteLine(ORIGINAL_TEXT);
            writer.Close();

            //Launch the external process.
            externalProcess = Process.Start(
                                    new ProcessStartInfo(PROCESS, PARAMS));

            //Wait for process to finish.
            while (!externalProcess.HasExited)
                    Thread.Sleep(0);        
            externalProcess.Dispose();

            //Read new content.
            reader = new StreamReader(FILENAME);
            newContent = reader.ReadToEnd();
            reader.Close();

            Console.WriteLine(newContent);
            Console.ReadLine();
            }
         }
    }

    Sam Jones
    Adaptive Intelligence
    http://www.adaptiveintelligence.net
    Thursday, May 25, 2006 12:51 PM