Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 255
Ignacio Soler Garcia Avatar asked Dec 15 '10 14:12

Ignacio Soler Garcia


2 Answers

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.

like image 84
MrEyes Avatar answered Oct 06 '22 22:10

MrEyes


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.

like image 24
Brian Avatar answered Oct 06 '22 20:10

Brian