【发布时间】:2011-09-06 14:53:54
【问题描述】:
我正在开发 c# 应用程序,我正在从服务器机器下载包(zip 文件)。它正在正确下载,但最近我们的包数据发生了一些变化,即 flex 应用程序。通过使用 c#,我们正在下载它放入c盘或d盘。
现在有了新包装,我面临一些问题 无法从传输连接读取数据:无法对套接字执行操作,因为系统缺少足够的缓冲区空间或队列已满。
我的代码在下面
byte[] packageData = null;
packageData = touchServerClient.DownloadFile("/packages/" + this.PackageName);
public byte[] DownloadFile(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteSite.Url + url);
try
{
request.Method = "GET";
request.KeepAlive = false;
request.CookieContainer = new CookieContainer();
if (this.Cookies != null && this.Cookies.Count > 0)
request.CookieContainer.Add(this.Cookies);
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
// Console.WriteLine(response.StatusDescription);
Stream responseStream = webResponse.GetResponseStream();
int contentLength = Convert.ToInt32(webResponse.ContentLength);
byte[] fileData = StreamToByteArray(responseStream, contentLength);
return fileData;
}
public static byte[] StreamToByteArray(Stream stream, int initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
在上面的函数(StreamToByteArray)中,我收到错误消息 无法从传输连接读取数据:无法对套接字执行操作,因为系统缺少足够的缓冲区空间或队列已满。
请帮助我,因为我也不应该更改代码。
提前致谢 桑吉塔
【问题讨论】:
-
这个文件有多大?也许您正在耗尽可用内存?
-
看看this blog post 和this answer 看看是否有帮助。
标签: c# httpwebrequest