[英]What are the Equivalent methods to CopyTo() and WriteTo() in .Net Framework 3.5 and below?
I need to use .NetFramework3.5 for my application, but CopyTo()
and WriteTo()
methods are not available in 3.5. 我需要为我的应用程序使用.NetFramework3.5,但是CopyTo()
和WriteTo()
方法在3.5中不可用。 what are the equivalent methods in 3.5? 3.5中的等效方法是什么?
when I run the code with 3.5 it is throwing the following error: 当我用3.5运行代码时,抛出以下错误:
'System.IO.Stream' does not contain a definition for 'WriteTo' and no extension method 'WriteTo' accepting a first argument of type 'System.IO.Stream' could be found 'System.IO.Stream'不包含'WriteTo'的定义,并且找不到找到接受类型为'System.IO.Stream'的第一个参数的扩展方法'WriteTo'
Here is the code: 这是代码:
int fileId = 1;
foreach (string uri in uriList)
{
request = (HttpWebRequest)WebRequest.Create (baseURL + uri);
request.Headers.Add ("X", authenticateStr);
request.Accept = "application/pdf";
request.Method = "GET";
webResponse = (HttpWebResponse)request.GetResponse();
using (MemoryStream ms = new MemoryStream())
using (FileStream outfile = new FileStream("document_", FileMode.Create)) {
webResponse.GetResponseStream().WriteTo(ms);
if (ms.Length > int.MaxValue) {
throw new NotSupportedException("Cannot write a file larger than 2GB.");
}
outfile.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
}
Console.WriteLine("Done!");
Stream.CopyTo
was indeed added with .NET 4. Earlier versions of .NET are missing lots of helpful methods added in latter versions. .NET 4确实添加了Stream.CopyTo
早期版本缺少在后来的版本中添加的许多有用的方法。 .NET 4.5 continues to have lots of "obvious" method missing, I assume future versions will continue to add such helpers if MS perceive sufficient demand. .NET 4.5仍然缺少许多“显而易见的”方法,我认为如果MS认为有足够的需求,将来的版本将继续添加此类帮助程序。
There is no Stream.WriteTo
. 没有Stream.WriteTo
。 It only exists on some subclasses (eg. MemoryStream.WriteTo
which has existed since .NET 1.0). 它仅存在于某些子类中(例如,自.NET 1.0开始就存在的MemoryStream.WriteTo
)。
(I suspect Stream.CopyTo
was added as a common MemoryStream.WriteTo
but obviously using WriteTo
would be an API breaking change because, for example, reflection on it would give different results.) (我怀疑Stream.CopyTo
是作为常见的MemoryStream.WriteTo
添加的,但显然使用WriteTo
将是API的重大更改,因为例如对它的反射会给出不同的结果。)
If you need for CopyTo I use this extension 如果您需要CopyTo,请使用此扩展名
public static void CopyTo(this Stream input, Stream output)
{
// This method exists only in .NET 4 and higher
byte[] buffer = new byte[4 * 1024];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.