Should I check the response of WebClient.UploadFil

2019-04-06 16:36发布

问题:

I never used the WebClient before and I'm not sure if I should check the response from the server to know if the upload was successful or if I can let the file as uploaded if there is no exception.

If I should check the response how can I do that? Parsing resposeHeaders property?

Thanks in advance.

回答1:

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.



回答2:

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.



回答3:

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.



回答4:

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.