Home > Enterprise >  MemoryStream is not writing everything expected to the file
MemoryStream is not writing everything expected to the file

Time:10-10

My problem is to write some data about passangers to the MemoryStream and then copy it to the file. I need to realize it in two different methods. In methods I need to use Stream, then in Main function I use MemoryStream. So I wrote this code:

    public static void WriteToStream(Stream stream)
    {
        Random rnd = new();
        StreamWriter sw = new(stream);

        for (int i = 0; i < 100; i  )
        {
            sw.WriteLine(i);
            sw.WriteLine($"Passanger{i}");
            sw.WriteLine(rnd.Next(0, 2) == 1);
        }
    }

    public static void CopyFromStream(Stream stream, string filename)
    {
        using var fs = File.Open(filename, FileMode.OpenOrCreate);
        stream.CopyTo(fs);
    }

Main function:

MemoryStream ms = new();

StreamService.WriteToStream(ms);
ms.Seek(0, SeekOrigin.Begin);
StreamService.CopyFromStream(ms, "database.dat");

But when I open the file, I see that there is not all the passangers. I need to write 100 passangers (according to the cycle on the first method) but there is only 87 passangers. File looks like this:

//some other passangers from 0 to 82, everything is fine with them
83
Passanger83
False
84
Passanger84
False
85
Passanger85
True
86
Passanger86
False
87
Passanger87
T

As you see at the end of the file the True statement is broken and there is not enough passangers in this file. Can somebody tell me what is the problem?

P.S. I posted this code today already in another question but now I fixed previous problem. Now I have another problem with it so it is not a duplicate.

CodePudding user response:

Try set StreamWriter.AutoFlush property to true in your WriteToStream method:

StreamWriter sw = new(stream) { AutoFlush = true };

And add manual deletion of your file if it exists for proper overwrite:

public static void CopyFromStream(Stream stream, string filename)
{
    if (File.Exists(filename))
        File.Delete(filename);

     using var fs = File.Open(filename, FileMode.OpenOrCreate);
     stream.CopyTo(fs);
}

Tested and works well on many iterations.

  • Related