Is there any way to know which file has just now finished downloading from the DownloadFileCompleted event of WebClient.
Thanks in advance.
You can use UserState to do this. Something like this
WebClient client = new WebClient();
client.DownloadDataCompleted +=
new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync(new Uri("YourURL"), "YourIdentifier");
Handler
static void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
var calledBy = e.UserState; //This will be "YourIdentifier"
}
Hope this works for you.
When downloading file use webClient.DownloadFileAsync(uri, name, state) method.
This 3rd parameter (state) will be sent to your in the UserState property of the DownloadFileCompleted event arguments.
Just pass the uri or the file name there and you will have it back nicely :)
Related
First of all hello guys i just wanted to add button that downloads zip files from link and then unzips and i ran into problems i get this error:
"System.IO.IOException: 'The process cannot access the file
'C:\GTA\TEST.zip' because it is being used by another process.'"
It looks really simple but i can't solve it so i hope you guys help me. this is code:
private void button2_Click(object sender, EventArgs e)
{
string root = #"C:\GTA";
//this if directory doesn't exist
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
progressBar1.Value = 0;
WebClient webcl = new WebClient();
webcl.DownloadFileCompleted += Webcl_DownloadFileCompleted;
webcl.DownloadProgressChanged += Webcl_DownloadProgressChanged;
webcl.DownloadFileAsync(new Uri("https://download1474.mediafire.com/17r5hin4vceg/izkb8vk7pudg5g4/TEST.zip"), #"C:\GTA\TEST.zip");
string targetfolder = #"C:\GTA\UNZIPEDFolder";
string sourceZipFile = #"C:\GTA\TEST.zip";
ZipFile.ExtractToDirectory(sourceZipFile, targetfolder);
}
I'm no expert here, however you get the file asynchronosly without awaiting it.
DownloadFileAsync
So you make a call to extract the file while it's being downloaded.
You calling ExtractToDirectory before file will be actually downloaded, as file downloading is async. So, you need to await when downloading process will finish. To do so, you will need the following
make the whole event click handler async - private async void button2_Click(object sender, EventArgs e).
replace DownloadFileAsync which returns void and thus is not async/await-friendly with DownloadFileTaskAsync, which is awaitable.
Then you will able to await downloading with await webcl.DownloadFileTaskAsync(...args here...);
finally, you can remove DownloadFileCompleted subscription, as you may be sure that after await the file downloading is completed.
By the way, WebClient is considered as an old API and is not recommended for using in the new code. You may consider to switch to HttpClient.
To elaborate a bit on the two previous answers, you are in fact trying to unzip the file before you have downloaded it. You should change your code as follows:
private async void button2_Click(object sender, EventArgs e)
{
string root = #"C:\GTA";
//this if directory doesn't exist
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
progressBar1.Value = 0;
WebClient webcl = new WebClient();
webcl.DownloadFileCompleted += Webcl_DownloadFileCompleted;
webcl.DownloadProgressChanged += Webcl_DownloadProgressChanged;
await webcl.DownloadFileAsync(new Uri("https://download1474.mediafire.com/17r5hin4vceg/izkb8vk7pudg5g4/TEST.zip"), #"C:\GTA\TEST.zip");
string targetfolder = #"C:\GTA\UNZIPEDFolder";
string sourceZipFile = #"C:\GTA\TEST.zip";
ZipFile.ExtractToDirectory(sourceZipFile, targetfolder);
}
Note the async as well as the await before DownloadFileAsync().
Additionally, you might want to refactor that a bit and move the download / unzip part out of the Button Event Handler.
I am using this C# code in LINQPad 6 (Free Edition) to download data from a webpage
void Main()
{
string a = "https://www1.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp";
WebClient w = new WebClient();
w.DownloadStringAsync(new Uri(a));
w.DownloadStringCompleted += (s,e) => {
string t = (string)e.Result;
Console.WriteLine (t);
};
}
I am always getting the WebException - An error occurred while sending the request. The response ended prematurely.
Can anyone please kindly point out my mistake. Awaiting your reply.
Thank you.
I'm upload file and get upload progress like this:
using (var wc = new WebClient())
{
wc.UploadProgressChanged += FileUploadProgressChanged;
wc.Headers.Add(HttpRequestHeader.ContentType, "image/png");
wc.UploadFileAsync(new Uri(url), filePath);
}
...
private void FileUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
ProgressBarUpload.Value = e.ProgressPercentage;
}
But after 50% e.ProgressPercentage return -441850 and then immediately returns 100. Why is this happening?
My solution:
private void FileUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
ProgressBarUpload.Value = e.BytesSent * 100 / e.TotalBytesToSend;
}
I also found two questions similar to this, but I have not managed to solve the problem. But it can be useful to others:
WebClient UploadFileAsync strange behaviour in progress reporting (cause of the problem - problems with authorization)
Uploading HTTP progress tracking (cause of the problem - the third-party application)
Note. Аfter downloading the file we receive a response from the server, it would be better to display the download file is 95% and the remaining 5% leave to display the response from the server. And in the end after a successful download and response from the server, we will be 100%.
PS: In the code, I did not show it, just say to those who might need it.
I'm using a webclient on a windows phone 8 app, i have to sync some data with the webservice each minutes (or by pressing a button). I put my webclient in a private data of my object :
private WebClient client_summary;
At the launch of the app the client connects to the webservice :
client_summary = new WebClient();
client_summary.DownloadStringAsync(new Uri("random url" + info_conf.id));
client_sommaire.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadSummaryConf);
I recovered well data, but each time i want to re sync my webclient, data remain the same :(
DispatcherTimer TradeThread = new DispatcherTimer();
TradeThread.Interval = TimeSpan.FromSeconds(10);
TradeThread.Tick += new EventHandler(dispatcherTimer_Tick);
TradeThread.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
pivotMainList.Items.Clear();
summary.Children.Clear();
client_summary.DownloadStringAsync(new Uri("url" + info_conf.id));
}
private void client_DownloadSummaryConf(object sender, DownloadStringCompletedEventArgs e)
{
MessageBox.Show(e.Result);
}
e.Result remain the same, whereas if I restart my app the data sync correctly
I don't understand why the sync didn't work ...
Please tell me thanks in advance.
This is a caching issue - the Webclient class (and the HttpClient class if you chose to use that instead) caches server responses. The standard workaround is to append something that varies to your querystring.
For examples see:
How do you disable caching with WebClient and Windows Phone 7
Windows Phone 7 WebRequest caching?
I'm trying to make an asynchronous HTTP GET request using Webclient, however, the registered callback never gets called. I've also tried with the sync one, and it worked fine. What am I doing wrong?
WebClient asyncWebRequest;
public AsyncWebRequest(Uri url)
{
asyncWebRequest = new WebClient();
url = new Uri("http://www.google.com/");
// string test = asyncWebRequest.DownloadString(url); // this works
asyncWebRequest.DownloadStringCompleted += new DownloadStringCompletedEventHandler(asyncWebRequest_DownloadStringCompleted);
asyncWebRequest.DownloadStringAsync(url);
}
void asyncWebRequest_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
throw new NotImplementedException();
}
Maybe because you disposing the WebClient before it finished downloading. The code execution don't stop on asyncWebRequest.DownloadStringAsync(url); and you are disposing the WebClient object by closing the using statement.
try to dispose the WebClient on asyncWebRequest_DownloadStringCompleted.
results
The simpliest solution is to add Console.ReadKey() at the end of AsyncWebRequest(url) method. This way asyncWebRequest.DownloadStringAsync(url) will be able to retrieve data.