【问题标题】:Write file directly into TcpClient without storing it in memory将文件直接写入 TcpClient 而不将其存储在内存中
【发布时间】:2015-07-27 16:17:38
【问题描述】:

我有一个 1 GB 的文件需要写入 TcpClient 对象。在不将整个文件读入内存的情况下,最好的方法是什么?

【问题讨论】:

  • TransmitFile() API?正如其他人指出的那样,数据必须在某处遍历内存,但 TF() API 可以将这种缓冲隐藏在内核中。

标签: c# sockets network-programming tcpclient tcplistener


【解决方案1】:

您必须在某个时间点将其读入内存,尽管您显然不需要一次全部完成!

只需使用BinaryReader.Read 并一次读取“n”个字节,例如:

        BinaryReader reader = new BinaryReader(new FileStream("test.dat", FileMode.Open));
        int currentIndex = 0;
        byte[] buffer = new byte[100];

        while (reader.Read(buffer, currentIndex, 100) > 0)
        {
            //Send buffer
            currentIndex += 100;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多