将一个流的内容复制到另一个流的最佳方法是什么?有标准的实用方法吗?
当前回答
简单安全-从原始来源制作新流:
MemoryStream source = new MemoryStream(byteArray);
MemoryStream copy = new MemoryStream(byteArray);
其他回答
MemoryStream有.WriteTo(outstream);
. net 4.0在普通流对象上有. copyto。
net 4.0:
instream.CopyTo(outstream);
可能有一种方法可以更有效地做到这一点,这取决于您处理的是哪种流。如果可以将一个或两个流转换为MemoryStream,则可以使用GetBuffer方法直接处理表示数据的字节数组。这让你可以使用像Array这样的方法。CopyTo,它抽象了fryguybob提出的所有问题。你可以相信. net知道复制数据的最佳方式。
区分“CopyStream”实现的基本问题是:
读取缓冲区的大小 写入的大小 我们是否可以使用多个线程(在读取时写入)。
这些问题的答案导致了CopyStream的巨大不同的实现,这取决于您拥有的流的类型和您试图优化的内容。“最佳”实现甚至需要知道流正在读取和写入的具体硬件。
由于没有一个答案涉及从一个流复制到另一个流的异步方式,这里是我在端口转发应用程序中成功使用的一种模式,它将数据从一个网络流复制到另一个网络流。它缺乏异常处理来强调模式。
const int BUFFER_SIZE = 4096;
static byte[] bufferForRead = new byte[BUFFER_SIZE];
static byte[] bufferForWrite = new byte[BUFFER_SIZE];
static Stream sourceStream = new MemoryStream();
static Stream destinationStream = new MemoryStream();
static void Main(string[] args)
{
// Initial read from source stream
sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
}
private static void BeginReadCallback(IAsyncResult asyncRes)
{
// Finish reading from source stream
int bytesRead = sourceStream.EndRead(asyncRes);
// Make a copy of the buffer as we'll start another read immediately
Array.Copy(bufferForRead, 0, bufferForWrite, 0, bytesRead);
// Write copied buffer to destination stream
destinationStream.BeginWrite(bufferForWrite, 0, bytesRead, BeginWriteCallback, null);
// Start the next read (looks like async recursion I guess)
sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
}
private static void BeginWriteCallback(IAsyncResult asyncRes)
{
// Finish writing to destination stream
destinationStream.EndWrite(asyncRes);
}
. net Framework 4引入了新的系统流类的CopyTo方法。IO命名空间。使用此方法,我们可以将一个流复制到不同流类的另一个流。
这里有一个例子。
FileStream objFileStream = File.Open(Server.MapPath("TextFile.txt"), FileMode.Open);
Response.Write(string.Format("FileStream Content length: {0}", objFileStream.Length.ToString()));
MemoryStream objMemoryStream = new MemoryStream();
// Copy File Stream to Memory Stream using CopyTo method
objFileStream.CopyTo(objMemoryStream);
Response.Write("<br/><br/>");
Response.Write(string.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()));
Response.Write("<br/><br/>");
推荐文章
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和
- 我如何使用IValidatableObject?
- 如何指定最小值,但没有使用范围数据注释属性的最大小数?
- c# vs Java Enum(适合c#新手)
- c#消毒文件名
- 在EF中更新父实体时如何添加/更新子实体
- ASP。NET身份的默认密码散列器-它是如何工作的,它是安全的?
- 如何写一个JSON文件在c# ?
- 静态隐式运算符
- 不区分大小写列表搜索
- 'throw'和'throw new Exception()'的区别
- 不能在lambda表达式中使用ref或out参数
- c# int到字节[]