c# - 如何在 C# 中将大文件拆分成 block ?

标签 c# file tcp filestream

我正在通过网络制作一个简单的文件传输发送方和接收方应用程序。到目前为止,我所拥有的是发送方将文件转换为字节数组并将该数组的 block 发送给接收方。

这适用于最大 256mb 的文件,但对于以上任何内容,此行都会引发“系统内存不足”异常:

byte[] buffer = StreamFile(fileName); //This is where I convert the file

我正在寻找一种以 block 的形式读取文件然后写入该 block 的方法,而不是将整个文件加载到一个字节中。如何使用 FileStream 执行此操作?

编辑:

抱歉,这是我目前为止糟糕的代码:

    private void btnSend(object sender, EventArgs e)
    {
        Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


        byte[] fileName = Encoding.UTF8.GetBytes(fName); //file name
        byte[] fileData = null;
        try
        {
             fileData = StreamFile(textBox1.Text); //file
        }
        catch (OutOfMemoryException ex)
        {
            MessageBox.Show("Out of memory");
            return;
        }

        byte[] fileNameLen = BitConverter.GetBytes(fileName.Length); //length of file name
        clientData = new byte[4 + fileName.Length + fileData.Length];
        fileNameLen.CopyTo(clientData, 0);
        fileName.CopyTo(clientData, 4);
        fileData.CopyTo(clientData, 4 + fileName.Length);
        clientSock.Connect("172.16.12.91", 9050);
        clientSock.Send(clientData, 0, 4 + fileName.Length, SocketFlags.None);

        for (int i = 4 + fileName.Length; i < clientData.Length; i++)
        {
            clientSock.Send(clientData, i, 1 , SocketFlags.None);
        }

        clientSock.Close();
    }

这是我收到的方式(代码来自教程)

   public void ReadCallback(IAsyncResult ar)
    {

        int fileNameLen = 1;
        String content = String.Empty;
        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;
        int bytesRead = handler.EndReceive(ar);
        if (bytesRead > 0)
        {

            if (flag == 0)
            {
                Thread.Sleep(1000);
                fileNameLen = BitConverter.ToInt32(state.buffer, 0);
                string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
                receivedPath = fileName;
                flag++;
            }
                if (flag >= 1)
                {
                    BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
                    if (flag == 1)
                    {
                        writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
                        flag++;
                    }
                    else
                        writer.Write(state.buffer, 0, bytesRead);
                        writer.Close();
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReadCallback), state);
                }
        }
        else
        {
            Invoke(new MyDelegate(LabelWriter));
        }

    }

我真的很想知道如何分 block 读取文件,这样我就不需要将它转换为字节。

感谢到目前为止的回复,我想我开始明白了:D

最佳答案

只需用一个小缓冲区(我倾向于使用 16K 之类的缓冲区)重复调用 Read。请注意,对 Read 的调用最终可能会读取小于 的数量,而不是您请求的数量。如果您使用固定 block 大小并且需要内存中的整个 block ,您当然可以只使用该大小的数组。

在不知道如何发送文件的情况下,很难就如何构建代码给出很多建议,但可能是这样的:

byte[] chunk = new byte[MaxChunkSize];
while (true)
{
    int index = 0;
    // There are various different ways of structuring this bit of code.
    // Fundamentally we're trying to keep reading in to our chunk until
    // either we reach the end of the stream, or we've read everything we need.
    while (index < chunk.Length)
    {
        int bytesRead = stream.Read(chunk, index, chunk.Length - index);
        if (bytesRead == 0)
        {
            break;
        }
        index += bytesRead;
    }
    if (index != 0) // Our previous chunk may have been the last one
    {
        SendChunk(chunk, index); // index is the number of bytes in the chunk
    }
    if (index != chunk.Length) // We didn't read a full chunk: we're done
    {
        return;
    }
}

如果我更清醒一些,我可能会找到一种更易读的方式来编写这篇文章,但现在就这样吧。一种选择是从中间部分提取另一种方法:

// Attempts to read an entire chunk into the given array; returns the size of
// chunk actually read.
int ReadChunk(Stream stream, byte[] chunk)
{
    int index = 0;
    while (index < chunk.Length)
    {
        int bytesRead = stream.Read(chunk, index, chunk.Length - index);
        if (bytesRead == 0)
        {
            break;
        }
        index += bytesRead;
    }
    return index;
}

关于c# - 如何在 C# 中将大文件拆分成 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659189/

相关文章:

c++ - 创建用于写入 TCP 套接字的消息

c# - 是否存在 Dot.Net 4.5 异步计时器

c# - RadioButtonList 值的空引用异常

java - 读取.txt信息并将其加载到数组中

c# - 通过 TCP 发送/接收文件

.net - WCF 双工服务和 TCP 端口耗尽

c# - 通过反射获取接口(interface)属性

c# - 数字范围和字符的正则表达式

C++ 逐行读取文件但行类型为 CString 或 TCHAR

c - 链接文件而不是链接列表