WebClient.UploadData出现问题

时间:2011-05-19 04:54:36

标签: c# webclient.uploaddata

我有一个客户端 - 服务器类型的应用程序,服务器运行HttpListener,客户端使用WebClient.UploadData将数据上传到服务器。代码工作得很好(大数据缓冲区为60K及以上),除了一个安装,当数据缓冲区大小超过16384时,UploadData超时。这是我在客户端的代码:

internal bool UploadData(byte[] buffer, String file, String folder)
{
    try
    {
        String uri = "http://" + GlobalData.ServerIP + ":" + GlobalData.ServerHttpPort + "/upload:";
        NameValueCollection headers = new NameValueCollection();
        headers.Set("Content-Type", "application/octet-stream");
        headers.Set("Y-Folder", folder);
        headers.Set("Y-File", file);
        using (WebClient wc = new WebClient())
        {
            wc.Credentials = new NetworkCredential(WebUserName, WebPassword);
            wc.Headers.Add(headers);
            wc.UploadData(new Uri(uri), buffer);
            return true;
        }
    }
        catch (Exception ex)
        {
            GlobalData.ODS("Exception in UploadFile " + ex.Message);
            return false;
        }
    }

在服务器上

ODS(TraceDetailLevel.Level4, "Process upload ");
HttpListenerResponse response = e.RequestContext.Response;
String disp = "";
String fil = "";
String folder = "";
Stream body = e.RequestContext.Request.InputStream;
long len64 = e.RequestContext.Request.ContentLength64;
Encoding encoding = e.RequestContext.Request.ContentEncoding;
ODS(TraceDetailLevel.Level4, "Process upload " + len64 + " bytes encoding " + encoding.EncodingName);
NameValueCollection nvp = e.RequestContext.Request.Headers;
try
{
disp = nvp["Content-Disposition"];
fil = nvp["Y-File"];
folder = nvp["Y-Folder"];
}
catch { }
BinaryReader reader = new BinaryReader(body, encoding);
byte[] data = new byte[len64];
long total = 0;
while (true)
{
  int dataleft = data.Length - (int)total;
  int offset = (int)total;
  GlobalData.ODS("Reading binary stream offset=" + offset + " read dataleft=" + dataleft);
  int cnt = reader.Read(data, offset, dataleft);
  if (cnt <= 0)
  {
    break;
  }
  total += cnt;
  if (len64 <= total)
  {
    break;
  }
}
ODS(TraceDetailLevel.Level4, "Process upload: Got  data "+total+" should have="+len64);
if (total == len64)
{
  //process data

上述代码适用于除一个安装之外的所有代码。怎么了?

1 个答案:

答案 0 :(得分:5)

看起来我找到了问题的根源。这个有问题的安装在我的代码中失败,在运行我的HTTP服务器代码的计算机上安装了AVG Free Antivirus。如果我在该计算机上禁用AVG,我的代码可以运行。想知道是否有人遇到与AVG类似的问题。