Answered Writing to Text File

  • quinta-feira, 12 de abril de 2012 15:58
    Moderador
     
     

    I'm having trouble with what seems like it should be simple but I just can't get it to work.  Here are the facts:

    - I'm using the Dashboard service with Eddie.

    - I wrote some code in the Depth cam form that for each time a depth cam image is displayed on the form, it will also save the image to a file and also write a line to a text file for the encoder data.  Here's the code:

    public void SaveToVideo(int width, int height, short[] depthData, int leftencoder, int rightencoder)

            {
                Bitmap bmp = MakeDepthBitmap(width, height, depthData);
                Image<Bgr, byte> cvImage = new Image<Bgr, byte>(bmp);

                try
                {
                    counter++;

                    if (counter % 3 == 0)
                    {

                        sw.WriteLine("{0}   {1} {2}", counter, leftencoder, rightencoder);
                        cvImage.Save("DC" + counter.ToString() + ".bmp");
                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine("save2: " + e.Message);
                }
                finally
                {
                    bmp.Dispose();
                }
            }

    - All the code related to saving an image works fine (it actually uses an OpenCV wrapper called EmguCV for this.

    - The code related to writing to a text file does not work at all.  Essentially, I have the following code when the form opens: 

    sw = new StreamWriter("encoder_data.txt", false);

    - This code creates a blank text file but is never updated with new data.

    - At first I thought this is a threading issue but then I used the CCR code which I found here: http://blogs.msdn.com/b/pollrobots/archive/2008/07/22/ccr-utilities-part-1.aspx.  That too did the same thing after I made the necessary changes.

    Any help would be appreciated.

    Dan.


    Dan Sionov

Todas as Respostas

  • sexta-feira, 13 de abril de 2012 00:37
    Moderador
     
     Respondido

    Could it be simply that buffered writes are never making it to disk? Try adding a sw.Flush() somewhere appropriate (or even after every write).

    Another alternative, which is used in Paul’s blog post you mention, would be to create with appending and flush/dispose on every write as in:

    using (var sw = new StreamWriter(…, true)) { sw.WriteLine(…); }

    Hope that helps!

  • sexta-feira, 13 de abril de 2012 16:24
    Moderador
     
     

    You called it.  I just set sw.Autoflush = true and that did the trick.

    Thank you!!

    Dan.


    Dan Sionov