我正在尝试将.NET 2.0集成到MS SQL Server 2008中。我调用了一个API,我应该收到一个.zip作为响应。我将响应存储到Stream中,我想将此文件导出到物理.zip文件。我尝试使用C#和SQL(BCB或OLE)导出文件,并导致文件损坏。所以,我相信我在制作流时做错了。
C#代码如下:
private static byte[] GetStreamFileResult(Cookie loginCookie, Guid fileGuid, String baseUri)
{
byte[] output = null;
//String result = null;
string url = "some url"
CookieContainer cookies = new CookieContainer();
cookies.Add(new Uri(url), loginCookie);
WebRequest request = WebRequest.Create(url);
(request as HttpWebRequest).CookieContainer = cookies;
WebResponse response = request.GetResponse();
HttpWebResponse resp = response as HttpWebResponse;
Stream dataStream = response.GetResponseStream();
using (MemoryStream ms = new MemoryStream())
{
CopyStream(dataStream, ms);
output = ms.ToArray();
}
dataStream.Close();
response.Close();
return output;
}
导出zip的C#代码如下:
File.WriteAllBytes("C:\\folder\\t.zip", stream); // Requires System.IO
从流到流的副本:
public static void CopyStream(Stream input, Stream output)
{
if (input != null)
{
using (StreamReader reader = new StreamReader(input))
using (StreamWriter writer = new StreamWriter(output))
{
writer.Write(reader.ReadToEnd());
}
}
}
你的CopyStream
坏了。你需要谈二进制。您当前正在将二进制zip数据视为文本:
byte[] buffer = new byte[2048];
int bytesRead;
while((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) {
output.Write(buffer, 0, bytesRead);
}