Search code examples
c#webclient.uploaddata

Trouble with WebClient.UploadData


I have a client-server type application with the server running HttpListener and the client uploading data to the server using WebClient.UploadData. The code works quite well (whith large data buffers 60K and up) except one installation where UploadData times out when data buffer size is bigger that 16384. Here is my code on the client:

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;
        }
    }

On the server

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

The code above works well on all but one installation. What is wrong?


Solution

  • It looks like I found the source of the problem. This one installation in question that fails my code has AVG Free Antivirus installed on a computer that runs my HTTP server code. If I disable AVG on that computer my code works. Wondering if anybody runs into similar issues with AVG.