简体   繁体   中英

How can I write to a file instead of an in memory byte array?

At the moment I have this code, which recieves information over the network, stores it into an in-memory byte array, and then writes it out via a FileStream.

 StreamReader reader = new StreamReader(tcpClient.GetStream());

  // first message is file size
         string cmdFileSize = reader.ReadLine();

  // first message is filename
        string cmdFileName = reader.ReadLine();

        int length = Convert.ToInt32(cmdFileSize);
        byte[] buffer = new byte[length];
        int received = 0;
        int read = 0;
        int size = 1024;
        int remaining = 0;


   while (received < length)
        {
            remaining = length - received;
            if (remaining < size)
            {
                size = remaining;
            }

            read = tcpClient.GetStream().Read(buffer, received, size);
            received += read;
            if (read < size)
            {
                break;
            }
        }    

After this, "buffer" is written to a file via FileStream. This works well, but when I have files that are large, obviously that amount of memory gets taken up. I'd like to stream these files directly to disk, instead of writing to ram and then rewriting them to the hard drive.

How could I do this?

Couldn't you just use StreamWriter to stream the contents out to the file as they come in?

StreamReader reader = new StreamReader(tcpClient.GetStream());

// first message is file size
string cmdFileSize = reader.ReadLine();

// first message is filename
string cmdFileName = reader.ReadLine();

int length = Convert.ToInt32(cmdFileSize);
byte[] buffer = new byte[length];
int received = 0;
int read = 0;
int size = 1024;
int remaining = 0;

using (FileStream writer = File.OpenWrite("outfile.dat"))
{
    while (received < length)
    {
        remaining = length - received;
        if (remaining < size)
        {
            size = remaining;
        }

        read = tcpClient.GetStream().Read(buffer, 0, size);
        received += read;
        writer.Write(buffer, 0, size);

        if (read < size)
        {
            break;
        }
    }
}

Also, I think you have a bug in your code. I assume that you are using System.Net.Sockets.TcpClient which returns a NetworkStream object when you call GetStream() . In that case, the second argument to the Read method should probably always be 0. That argument indicates where in the buffer variable to start writing the data read from the network. If you don't use 0, you are likely to get array out of bounds exceptions. Check out the docs for the Stream.Read method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM