Search code examples
c#.netfilestreammemorystream

MemoryStream is not writing anything to the file


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); //true or false
        }
    }

    public static void CopyFromStream(Stream stream, string filename)
    {
        StreamReader sr = new(stream);
        StreamWriter sw = new(File.Open(filename, FileMode.OpenOrCreate));
        while (sr.BaseStream.Position < sr.BaseStream.Length)
        {
            sw.WriteLine(sr.ReadLine());
        }
        sw.Close();
    }

Main function:

MemoryStream ms = new();

StreamService.WriteToStream(ms);
StreamService.CopyFromStream(ms, "database.dat");

First method is writing some data about passangers to the stream, the other is reading it and writing it to the file. But when I check my file, it is empty. What could be the problem?


Solution

  • After writing to MemoryStream it's Position is at the end. You need to set position back to the beginning:

    WriteToStream(ms);
    ms.Seek(0, SeekOrigin.Begin); // < here
    CopyFromStream(ms, "database.dat");
    

    Also, Stream class already has CopyTo method so there is no need to reinvent it (except maybe you are on some very old framework vesrion where it's not available?):

    WriteToStream(ms);
    ms.Seek(0, SeekOrigin.Begin); // < here
    using (var fs = File.Open("database.dat", FileMode.OpenOrCreate)) {
        ms.CopyTo(fs);
    }