从asp.net返回一个字节数组并从C#应用程序下载它

时间:2013-08-05 17:40:58

标签: c# asp.net-mvc-4

所以我有一个asp.net应用程序,它在GET请求上写一个字节数组,我正在尝试在C#应用程序中接收该字节数组。但是当我尝试下载时,我似乎只收到了标题。 (totalBuff)

我不是最好的解释,但我希望代码能让它更清晰。

ASP.NET代码:

var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StreamContent(new FileStream("D:\\Temp\\uLockStub.dll", FileMode.Open));
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return resp;

C#代码:

var httpReq = (HttpWebRequest)
WebRequest.Create(string.Format("http://localhost:48976/login/login?user={0}&password={1}&hwid={2}",
                                        username, Helper.GetMd5Hash(password), uid));
var resp = httpReq.GetResponse();
var data = resp.GetResponseStream();

var buff = new byte[1024];
var totalBuff = new List<byte>();
var read = 0;

while ((read = data.Read(buff, 0, buff.Length)) > 0)
   {
      var tmpBuff = new byte[read];
      Buffer.BlockCopy(buff, 0, tmpBuff, 0, read);
      totalBuff.AddRange(tmpBuff);
   }

我做错了什么?

提前致谢!

1 个答案:

答案 0 :(得分:1)

解决:

更换

var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StreamContent(new FileStream("D:\\Temp\\uLockStub.dll", FileMode.Open));
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return resp;

Response.BinaryWrite(System.IO.File.ReadAllBytes("D:\\Temp\\uLockStub.dll"));

解决了它。