Terrii
Terrii

Reputation: 385

Convert uploadfile to uploadfileasync c#

Hello I'm trying to upload a file to my web server via c# and I'm having a problem when uploading the file my application freezes until file is done uploading and I wanted to upload it Async but I cannot seem to get the code to work here is there code and the error I keep getting.

This code works but freezes the form.

WebClient wc = new WebClient();
wc.Credentials = new System.Net.NetworkCredential(TxtUsername.Text, TxtPassword.Text);
string Filename = TxtFilename.Text;
string Server = TxtServer.Text + SafeFileName.Text;
wc.UploadFile(Server, Filename);

But if i do this code I get an error.

WebClient wc = new WebClient();
wc.Credentials = new System.Net.NetworkCredential(TxtUsername.Text, TxtPassword.Text);
string Filename = TxtFilename.Text;
string Server = TxtServer.Text + SafeFileName.Text;
wc.UploadFileAsync(Server, Filename);

and I get this error when trying to make it Async

Error 1 The best overloaded method match for System.Net.WebClient.UploadFileAsync(System.Uri, string)' has some invalid arguments.
Error 2 Argument 1: cannot convert from 'string' to 'System.Uri'

Upvotes: 0

Views: 937

Answers (2)

e_ne
e_ne

Reputation: 8469

As Kami said. Furthermore, you might want to handle the UploadFileCompleted event.

Example:

wc.UploadFileCompleted += (o, args) =>
{
    //Handle completition
};
wc.UploadFileAsync(new Uri(Server), Filename);

Upvotes: 3

Kami
Kami

Reputation: 19437

Change the line

wc.UploadFileAsync(Server, Filename);

to

wc.UploadFileAsync(new Uri(Server), Filename);

UploadFileAsync does not take a string argument, so you need to create a Uri from the server address. See the MSDN Docs for more details.

Upvotes: 6

Related Questions