1

我正在使用如下所示的 UploadFilesAsync 方法上传文件。

var wc = new WebClient();
Uri myUri = new Uri(uriString);
wc.UploadFileAsync(myUri, "POST", filePath);
wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(wc_UploadFileCompleted);

我的 UploadFileCompleted 事件处理程序被调用,但由于某种原因 UploadProgressChanged 事件处理程序从未被调用。

任何想法为什么?

4

2 回答 2

1

改变:

wc.UploadFileAsync(myUri, "POST", filePath);
wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(wc_UploadFileCompleted);

为了:

wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(wc_UploadFileCompleted);
wc.UploadFileAsync(myUri, "POST", filePath);

在 UploadFileAsync 调用之后绑定事件,您必须首先绑定事件处理程序。

MSDN 示例:

// Sample call: UploadFileInBackground2("http://www.contoso.com/fileUpload.aspx", "data.txt")
public static void UploadFileInBackground2 (string address, string fileName)
{
    WebClient client = new WebClient ();
    Uri uri = new Uri(address);

    client.UploadFileCompleted += new UploadFileCompletedEventHandler (UploadFileCallback2);

     // Specify a progress notification handler.
     client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
    client.UploadFileAsync (uri, "POST", fileName);
    Console.WriteLine ("File upload started.");
}
于 2012-12-03T21:54:48.563 回答
0

您应该首先添加 eventHandlers,然后调用将触发它们的方法。

wc.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
wc.UploadFileCompleted += new UploadFileCompletedEventHandler(wc_UploadFileCompleted);
wc.UploadFileAsync(myUri, "POST", filePath);
于 2012-12-03T22:02:37.740 回答