Should I check the response of WebClient.UploadFile to know if the upload was successful?

早过忘川 提交于 2019-12-04 02:03:42

The UploadFile method returns a byte[] that contains the response the remote server returned. Depending on how the server manages responses to upload requests (and error conditions (see note 1 below)) you will need to check that response. You can get the string response by converting it to a string, for example this will write the response to the console window:

byte[] rawResponse = webClient.UploadFile(url,fileName);
Console.WriteLine("Remote Response: {0}", System.Text.Encoding.ASCII.GetString(rawResponse));

That said if the remote server returns anything other than a HTTP 200 (i.e. success) the call to UploadFile will throw a WebException. This you can catch and deal with it whatever manner best suits your application.

So putting that all together

try
{
    WebClient webClient = new WebClient();
    byte[] rawResponse = webClient.UploadFile(url,fileName);

    string response = System.Text.Encoding.ASCII.GetString(rawResponse);

    ...
    Your response validation code
    ...
}
catch (WebException wexc)
{
    ...
    Handle Web Exception
    ...
}

Note 1 As an example I have a file upload service that will never issue anything other than a HTTP 200 code, all errors are caught within the service and these are "parsed" into an XML structure that is returned to the caller. The caller then parses that XML to validate that the upload was successful.

If the upload returns a StatusCode other than 200 (or 200 range), WebClient.UploadFile should raise a WebException.

As a plug, I have a code reference library on BizArk that includes a WebHelper class that makes it easy to upload multiple files and form values at the same time. The project is called BizArk.

In the examples provided at msdn they check the response so it might be good style, but I tend not to do it myself and haven't gotten burned yet.

You also can use async method UploadFileAsync and check results in event handler UploadFileCompletedEventHandler occurred from event UploadFileCompleted. You probably have to add additional code for synchronization.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!