How to capture any error with Webclient? - c#

Im trying to capture connection problem when using WebClient. Example, unreachable, timeout etc. Code belows doesnt work, as if there is nothing wrong.
WebClient wc = new WebClient();
try
{
wc.UploadFileAsync(new Uri(#"ftp://tabletijam/FileServer/upload.bin"), Directory.GetCurrentDirectory() + #"\crypto.bin");
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}

The code you are using, just sends the file ... you need to implement the Async part.
WebClient webClient = new WebClient();
webClient.UploadFileAsync(address, fileName);
webClient.UploadProgressChanged += WebClientUploadProgressChanged;
webClient.UploadFileCompleted += WebClientUploadCompleted;
...
void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
Console.WriteLine("Download {0}% complete. ", e.ProgressPercentage);
}
void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
// The upload is finished, clean up
}

try
{
// trying to make any operation on a file
}
catch (IOException error)
{
if(error is FileNotFoundException)
{
// Handle this error
}
}
use this code but with your scenario

Related

C#Webclient downloadfileasync not working

/// <summary>
/// 下载更新
/// </summary>
public string Update()
{
string result = "";
try
{
if (!isUpdate)
return result;
WebClient wc = new WebClient();
string filename = "Update_NewVersion.zip";
filename = Path.GetDirectoryName(loadFile) + "\\" + filename;
FinalZipName = filename;
//wc.DownloadFile(download, filename);//能下载成功
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileAsync(new Uri(download), filename);//使用DownloadFileAsync下载不成功,能正常运行代码,但是执行后没有下载到zip文件,
//wc.Dispose();
return result = "download:" + download + ",filename:" + filename;
}
catch (Exception ex)
{
throw new Exception("更新出现错误,网络连接失败!" + ex.Message);
}
}
void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
(sender as WebClient).Dispose();
if (e.Error != null)
throw e.Error;
else
isFinish();
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
CommonMethod.autostep = e.ProgressPercentage;
//Thread.Sleep(100);
}
The download file code using downloadfileasync works normally, but it is not downloaded to the file after execution. It has been tested that downloadfile can be downloaded to the file normally。
Is it because the program completed the running before the download finished? It is a possible reason if your app is a console application.
Following comes from mdsn:
https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadfileasync?view=net-5.0
This method does not block the calling thread while the resource is being downloaded. To block while waiting for the download to complete, use one of the DownloadFile methods.

How to download and run a .exe file c#

Before you flag this as a duplicate, yes there are questions just like this, i've looked at all of them and still couldn't get this working. I'm trying to code in a feature that downloads and runs a .exe file but it doesn't download, run or do anything. I even removed the try catches to find an error or error codes but I have non, so I have no idea where i'm going wrong, here is my code for it
public test_Configuration()
{
InitializeComponent();
}
Uri uri = new Uri("http://example.com/files/example.exe");
string filename = #"C:\Users\**\AppData\Local\Temp\example.exe";
private void button1_Click(object sender, EventArgs e)
{
try
{
if(File.Exists(filename))
{
File.Delete(filename);
}
else
{
WebClient wc = new WebClient();
wc.DownloadDataAsync(uri, filename);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (progressBar1.Value == progressBar1.Maximum)
{
progressBar1.Value = 0;
}
}
private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if(e.Error == null)
{
MessageBox.Show("Download complete!, running exe", "Completed!");
Process.Start(filename);
}
else
{
MessageBox.Show("Unable to download exe, please check your connection", "Download failed!");
}
Change DownloadDataAsync to DownloadFileAsync.
wc.DownloadFileAsync(uri, filename);
This code helped me out quite a bit with updating a file, so I thought I would show my twist in the hopes that someone else out there has a similar requirement as me.
I needed this code to do the following when a button was clicked:
Grab a file from a sever and store it locally in AppData\Temp.
Keep my user up-to-date of install progress (an installer is downloaded).
If successfully downloaded (note the removal of the else after deleting old file check), launch "daInstaller.exe", whilst terminating the current running program.
And if said file already exist (i.e. the old "daIstaller.exe"), delete prior to copying new file to AppData\Temp.
Don't forget to keep the file names the same, else you'll be leaving more trash in that AppData\Temp folder.
private void button1_Click(object sender, EventArgs e)
{
Uri uri = new Uri("http://example.com/files/example.exe");
filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp/example.exe");
try
{
if (File.Exists(filename))
{
File.Delete(filename);
}
WebClient wc = new WebClient();
wc.DownloadFileAsync(uri, filename);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (progressBar1.Value == progressBar1.Maximum)
{
progressBar1.Value = 0;
}
}
private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
Process.Start(filename);
Close();
Application.Exit();
}
else
{
MessageBox.Show("Unable to download exe, please check your connection", "Download failed!");
}
}

BackgroundWorker not starting again when once finished

I have a WinForms application which uses a backgroundworker for downloading images from given urls. For the download I use a backgroundworker.
The application is running fine when started, and the download happens as planned, but when the worker is done and I click the downloadbutton again to start downloading from another url, the backgroundworker doesn't do anything.
I fixed that problem temporarily by calling application.restart() when the worker is done, which works but can't be here longer than it has to.
Worker-Code:
// initialization of worker is done in constructor of my class
downloadWorker.WorkerReportsProgress = true;
downloadWorker.WorkerSupportsCancellation = true;
downloadWorker.DoWork += new DoWorkEventHandler(worker_doWork);
downloadWorker.ProgressChanged += new ProgressChangedEventHandler(worker_progressChanged);
downloadWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_runWorkerCompleted);
// ...
private void worker_doWork(object sender, DoWorkEventArgs e)
{
WebClient downloadClient = new WebClient();
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response;
try
{
response = (HttpWebResponse)HttpReq.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}
if (response.StatusCode == HttpStatusCode.NotFound)
MessageBox.Show("Website not found");
if (response.StatusCode == HttpStatusCode.OK)
{
for(int i=0; i<3;i++)
{
string image = getImageUrl(url,i);
downloadWorker.ReportProgress(i);
image = WebUtility.HtmlDecode(image);
string saveName = "img_"+i+".png";
try
{
downloadClient.DownloadFile(image, saveName);
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
}
}
}
private void worker_progressChanged(object sender, ProgressChangedEventArgs e)
{
rtxtStatus.AppendText("Downloade Image" + e.ProgressPercentage + " of 3");
}
private void worker_runWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Download completed");
}
edit:
if (e.Error != null)
{
MessageBox.Show(e.Error.ToString());
}
To avoid any misunderstandings: The backgroundWorker is definetely running at the second time, and it is not an error of the reportProgress-method, since I get the same thing when I dont report anything.
edit no. 2:
I found out where the error came from: at the second run, the for-loop is completely skipped. But that doesn't make any sense for me either... There can't be any other value still be in because I have a completely new instance of the class, can it? But anyway, if it just skipped the method the worker still should exit which it doesn't do. For testing, I added a MessageBox after the for-loop, which is not executed after the second run.

HttpWebRequest making duplicate request?

I'm running my program as a windows service and I'm trying to send a HTTP request everytime the time elapsed(i've set to 1 minute). What I'm trying to do at the server side is just writing a value that it gets from the query string. The writing to file works but i noticed there is some duplicate values being sent?
protected override void OnStart(string[] args)
{
try
{
eventLog1.WriteEntry("In OnStart, this is another new build 016");
timer1 = new System.Timers.Timer(5000D);
timer1.AutoReset = true;
timer1.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer1.Start();
eventLog1.WriteEntry("This is after calling start method");
}
catch (Exception exxx)
{
eventLog1.WriteEntry(exxx.Data.ToString());
}
}
protected override void OnStop()
{
eventLog1.WriteEntry("In onStop.");
}
private static void timer_Elapsed(object source, ElapsedEventArgs e)
{
timer1.Stop();
el.WriteEntry("The Elapsed event was raised at " + i);
i++;// i is initialized to 0
request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("http://www.example.com/Test.php?test=" + i);
request.Method = "GET";
request.Timeout = 5000;
try
{
request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);
}
catch (System.Net.WebException e1)
{
el.WriteEntry("Exception 1:" + e1.Message);
}
catch (System.Net.ProtocolViolationException e2)
{
el.WriteEntry("Exception 2:" + e2.Message);
}
catch (System.InvalidOperationException e3)
{
el.WriteEntry("Exception 3:" + e3.Message);
}
timer1.Start();
}
private static void FinishWebRequest(IAsyncResult result)
{
request.GetResponse().Close();
}
What i noticed in my file is something like 1,2,1,1,3,2,2,1,1. I don't see anything wrong with my code. Is it possible that the HttpWebRequest is sending duplicate request?
In my opinion code is correct.I think you are using i variable somewhere else also.
Try changing i to something else which is not so common
HttpWebRequest never sends same request duplicate request.
For an instance let us assume that HttpRequest are duplicated then output should be something like 1,1,1,1,2,2,2,3.....

Getting NotFound trying to access google.com with WebClient

the problem is : the remote server returned an error :NotFound
private WebClient client = new WebClient();
private string siteUrl = "http://www.google.com/";
// Constructor
public MainPage()
{
InitializeComponent();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(siteUrl));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (e.Error == null)
{
webClientResults.Text = e.Result;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Check the network connectivity in your device. Such error occurs mainly when there is no proper internet connectivity is not available.
There is no problem in your code.

Categories

Resources