1

I'm trying to upload a file using WebClient, but I can't seem to find a way to get the response headers once the file is uploaded I'm using this Microsoft example to get the headers, but it just returns null. My code looks like this:

public void UploadPart(string filePath, string preSignedUrl)
{
   WebClient wc = new();
   wc.UploadProgressChanged += WebClientUploadProgressChanged;
   wc.UploadFileCompleted += WebClientUploadCompleted;
   wc.UploadFileAsync(new Uri(preSignedUrl), "PUT", filePath);

   // Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
   WebHeaderCollection myWebHeaderCollection = wc.ResponseHeaders;

   System.Diagnostics.Debug.WriteLine(myWebHeaderCollection);
}

I can confirm that the headers exist because I'm able to get them using an HttpWebResponse upload implementation in another method.

1 Answer 1

1

Method should be written like this.

public Task UploadPart(string filePath, string preSignedUrl)
{
   WebClient wc = new();
   wc.UploadProgressChanged += WebClientUploadProgressChanged;
   wc.UploadFileCompleted += WebClientUploadCompleted;
   await wc.UploadFileAsync(new Uri(preSignedUrl), "PUT", filePath);

   // Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
   WebHeaderCollection myWebHeaderCollection = wc.ResponseHeaders;

   System.Diagnostics.Debug.WriteLine(myWebHeaderCollection);
}

Replace void with Task. Use await in UploadFileAsyn because it may possible without request complete code jump to next line.

Sign up to request clarification or add additional context in comments.

2 Comments

I just tried this, and it seems I need to add the async keyword to UploadPart or the method shows an error that await can only be used in an async member. When I do however, await wc.UploadFileAsync(new Uri(preSignedUrl), "PUT", filePath); displays the error: "Cannot await void"
Looks like I needed to use UploadFileTaskAsync in place of UploadFileAsync. In doing so, your code above works great. Could you edit your answer to use UploadFileTaskAsync and I'll mark it as correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.