如何写入文件而不是内存中的字节数组

本文关键字:字节 字节数 数组 内存 何写入 文件 | 更新日期: 2023-09-27 18:16:39

目前我有这段代码,它通过网络接收信息,将其存储到内存中的字节数组中,然后通过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;
            }
        }    

在此之后,"buffer"通过FileStream写入文件。这工作得很好,但是当我有很大的文件时,显然会占用大量的内存。我想把这些文件直接流式传输到磁盘上,而不是写入ram,然后再重写到硬盘上。

我怎么能这么做?

如何写入文件而不是内存中的字节数组

难道不能使用StreamWriter在文件输入时将内容流式传输到文件中吗?

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;
        }
    }
}

还有,我认为你的代码有bug。我假设你使用的是System.Net.Sockets.TcpClient,当你调用GetStream()时,它返回一个NetworkStream对象。在这种情况下,Read方法的第二个参数可能总是为0。该参数指示在buffer变量中开始写入从网络读取的数据的位置。如果不使用0,很可能会得到数组越界异常。查看Stream.Read方法的文档