It is interesting. Looking at the source (WebClient.cs), the first line of UploadFileAsyncWriteCallback passes the state parameter to UploadBitsState .
The UploadFileAsync method has an exception handling code that reads:
catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if(fs != null){ fs.Close(); } if (!(e is WebException || e is SecurityException)) { e = new WebException(SR.GetString(SR.net_webclient), e); } UploadFileAsyncWriteCallback(null, e, asyncOp); }
asyncOp is of type AsyncOperation .
It seems that calling UploadFileAsyncWriteCallback here is an error, as it passes the wrong type object to the callback. The callback performs a C-style listing (i.e. UploadBitsState uploadState = (UploadBitsState)state; ).
But this will only happen if something throws an exception at boot time.
Is it possible that something in your ProgressChanged or UploadCompleted event handlers throws an exception? Either this, or one of the parameters that you pass to UploadFileAsync is invalid.
Additional Information
Actually, it looks like a bug in UploadFileAsync . For example, the following throws an InvalidCastException when, according to the documentation, it should throw a WebException .
var targetUri = new Uri("ftp://example.com/file.txt"); var srcFile = string.Empty; // documentation says this will throw WebException var client = new WebClient(); client.UploadFileAsync(targetUri, "STOR", srcFile, null);
I reported an error at https://connect.microsoft.com/VisualStudio/feedback/details/675575/webclient-uploadfileasync-throws-invalidcastexception
However, in terms of things, I would say that the reason the exception is thrown lies in your code. Unfortunately, it is impossible to say where, because UploadFileAsync loses exception information. Perhaps, as someone else noted, an attempt to synchronize download would shed more light on this topic.