【问题标题】:FileStream.copyTo(Net.ConnectStream) what happens intern?FileStream.copyTo(Net.ConnectStream) 实习生会发生什么?
【发布时间】:2013-05-02 15:14:40
【问题描述】:

这段代码运行良好。我的问题是当我使用 CopyTo() 方法时 Net.ConnectionStream 中会发生什么?

System.Net.HttpWebRequest request 
using (FileStream fileStream = new FileStream("C:\\myfile.txt")
{                        
    using (Stream str = request.GetRequestStream())
    {                   
         fileStream.CopyTo(str);
    }
}

更具体:数据会发生什么变化?
1.写入内存然后上传呢? (大文件有什么用?) 2.直接写入网络? (这是如何工作的?)

感谢您的回答

【问题讨论】:

  • 从 MSDN 开始,CopyTo 方法将逐字节写入目标 Stream
  • 你试过反编译吗? IL Spy

标签: c# stream connection filestream


【解决方案1】:

它创建一个byte[] 缓冲区并在源上调用Read,在目标上调用Write,直到源不再有数据为止。

因此,对大文件执行此操作时,您无需担心内存不足,因为您只会分配缓冲区大小,默认为 81920 字节。

这是实际的实现 -

public void CopyTo(Stream destination)
{
    // ... a bunch of argument validation stuff (omitted)
    this.InternalCopyTo(destination, 81920);
}

private void InternalCopyTo(Stream destination, int bufferSize)
{
    byte[] array = new byte[bufferSize];
    int count;
    while ((count = this.Read(array, 0, array.Length)) != 0)
    {
        destination.Write(array, 0, count);
    }
}

【讨论】:

    猜你喜欢
    • 2018-03-02
    • 1970-01-01
    • 2010-09-26
    • 2021-01-06
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    相关资源
    最近更新 更多