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.
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.