c# - WebClient.UploadData 出现问题

标签 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

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

最佳答案

看来我找到了问题的根源。这个导致我的代码失败的安装在运行我的 HTTP 服务器代码的计算机上安装了 AVG Free Antivirus。如果我在那台计算机上禁用 AVG,我的代码就可以工作。想知道是否有人在使用 AVG 时遇到类似问题。

关于c# - WebClient.UploadData 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6053935/

相关文章:

c# - StyleCop/FxCop 10 - 如何仅在 namespace 级别正确抑制消息?

c# - 索引超出范围。必须是非负误差

c# - [必填] 有什么作用?

c# - 在 C# 中设置 Windows 混音器音量控制需要使用什么库?

c# - 将焦点设置到 uwp 中的文本框

rest - 从 ajax 调用同时发送的重复 webClient 请求

MySQL:LOAD DATA LOCAL INFILE 添加额外字符 '\r'

C#远程web请求证书报错

asp.net - asp.net webclient 中 UploadData 和 DownloadString 之间的基本区别是什么?