The difference between aync and normal transfer is, that the UploadValues
method will block the current thread until all data has been transferred. Because the thread is blocked in this time you can't catch any events too. Therefore you have to use the asynchrony method UploadValuesAsync
which will transfer the data in the background and you're able to go on with the execution of your code.
The UploadProgressChanged
only fires for the UploadValuesAsync
too. Your code should look something like this (Not tested!):
public String UploadImage(string image)
{
WebClient w = new WebClient();
w.UploadProgressChanged += (s, e) =>
{
myProgressBar.Maximum = (int)e.TotalBytesToSend;
myProgressBar.Value = (int)e.BytesSent;
};
w.UploadValuesCompleted += new UploadValuesCompletedEventHandler(UploadComplete);
w.Headers.Add("Authorization", "Client-ID " + ClientId);
System.Collections.Specialized.NameValueCollection Keys = new System.Collections.Specialized.NameValueCollection();
try
{
Keys.Add("image", Convert.ToBase64String(File.ReadAllBytes(image)));
w.UploadValuesAsync("https://api.imgur.com/3/image", Keys);
return "Uploading..";
} catch (Exception s)
{
MessageBox.Show("Something went wrong. " + s.Message);
return "Failed!";
}
}
public void UploadComplete(Object sender, UploadValuesCompletedEventArgs e)
{
myProgressBar.Value = 100;
byte[] responseArray = e.Result;
dynamic result = Encoding.ASCII.GetString(responseArray);
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("link\":\"(.*?)\"");
System.Text.RegularExpressions.Match match = reg.Match(result);
string url = match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/");
textBox1.Text = url;
}
Edit
I moved the code after the UploadValuesAsync
call into the w.UploadValuesCompleted
. You can find the server response in the Result
field of the UploadValuesCompletedEventArgs
class which is passed to the event in the variable e
.
Your method UploadImage
will now return Uploading when the progress started and you'll have to do your rest work in the w.UploadValuesCompleted
event.