C# – WebClient.UploadFile() throws exception on some binary files


I am using the WebClient.UploadFile() method to post files to a service for processing. The file contains an XML document with a compressed, b64-encoded content element in it. For some files (currently 1), the UploadFile throws an exception, indicating that the underlying connection was closed. The innermost exception on socket level gives the message 'An existing connection was forcibly closed by the remote host'.


  1. Has anyone necountered the same problem?
  2. Why does it throw an exception for some files, and not for all?
  3. Should I set some additional parameter for files with binary content?
  4. Is there a workaround?

This functionality does work fine in a VPN situation, but obviously we want to use it to work in standard Internet situations.

Thanks, Rine

Best Solution

Sounds like a firewall or other security software sitting in between you and the server may be rejecting the request as a potential attack. I've run into this before where firewalls were rejecting requests that contained a specific file extension-- even if that file extension was encoded in a query string parameter!

If I were you, I'd take the problematic file and start trimming XML out of it. You may be able to find a specific chunk of XML which triggers the issue. Once you've identified the culprit, you can figure out how to get around the issue (e.g. by encoding those characters using their Unicode values instead of as text before sending the files). If, however, any change to the file causes the problem to go away (it's not caused by a specific piece of worrisome text), then I'm stumped.