I'm trying to download zend-framework (from http://framework.zend.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip) simply using WebClient
string url = "http://framework.zend.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip";
WebClient downloader= new WebClient();
downloader.DownloadFileAsync(new Uri(url), "C:\\temp.zip");
The file is created, but it is empty. I checked response using fiddler and I get HTTP 200, correct content-length but "connection: closed" and fiddler shows "-1" in "body" column.
I have tried adding user agent (copied from google chrome request) and "connection: keep-alive" to headers, but none of these helped. I'm also pretty sure, that my program downloaded this file using the same URL once or twice before. There are no errors in events fired by WebClient.
Any ideas?
Ok, I finnaly found the answer! Before downloading the file, I was checking its size by sending HttpWebRequest. The problem was, that i didn't Close() the response.
Thanks for the answers, they were nice clues.
Just my guess: maybe you can try to keep the WebClient instance in some place would not be garbage collected. When the DownloadFileCompleted event fired, you just clean the reference to the WebClient instance and let GC to reclaim the memory later (and don't forget to call Dispose method).
Try to handle the DownloadProgressChanged and DownloadFileCompleted event.
private void button1_Click(object sender, EventArgs e)
{
string url = "http://framework.zend.com/releases/ZendFramework-1.11.11/ZendFramework-1.11.11.zip";
WebClient downloader = new WebClient();
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(downloader_DownloadFileCompleted);
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
downloader.DownloadFileAsync(new Uri(url), "C:\\temp.zip");
}
void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
label1.Text = e.BytesReceived + " " + e.ProgressPercentage;
}
void downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
MessageBox.Show(e.Error.Message);
else
MessageBox.Show("Completed!!!");
}
If you have UAC enabled in Windows "C:\temp.zip" in the following line will fail to save the file because you aren't allowed to write outside of user directories without elevated permissions:
downloader.DownloadFileAsync(new Uri(url), "C:\\temp.zip");
Related
So I'm creating a program that can go into google and search for the word that has
been saved into a variable. So my question is how I can do this, without having it go to a URL instead just going to Google and search "whatever" Here's the code.
private void button2_Click(object sender, EventArgs e)
{
if (Script.Text == Script.Text)
{
Console.AppendText("\n[1] Loading Websites of " + Script.Text + "...");
}
WebClient wc = new WebClient();
Process.Start(#"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "Scripts " + Script.Text);
}
This should solve your problem
public static void GoToSite(string url)
{
System.Diagnostics.Process.Start("chrome.exe", url);
}
you can also change browser dynamically by adding a second params
You can also do this:
String stringToSearch = “stackoverflow”;
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + stringToSearch);
This assumes IE is the default browser on your machine. If Chrome or Firefox is the default browser, then code will fail.
This is a useful link:
http://www.seirer.net/blog/2014/6/10/solved-how-to-open-a-url-in-the-default-browser-in-csharp
Maybe you can put it in a try catch block and see if there is an exception. If there is an exception with starting IE, then open chrome.
I am working on an application that will download a .zip file from my server and extract it when the download is complete using DotNetZip 1.9
The application is downloading the zip file properly, but when it gets to the section to read the .zip file it throws the exception "Cannot read that as a zip file" (full exception at http://pastebin.com/NTrtMgR9).
What throws me off, is even tho it is throwing an exception, the file is still unzipped properly...
Here is my source:
private void btnDownload_Click(object sender, EventArgs e)
{
if (!Directory.Exists(HardCorpsPath))
{
//MessageBox.Show("Downloading HardCorps Mod Pack (Full)", "Downloading", MessageBoxButtons.OK, MessageBoxIcon.Information);
zipFileName = "HardCorps";
HCDownloadURL = String.Format("http://www.survivaloperations.net/client/hardcorps/{0}.zip", zipFileName);
HCZipPath = Path.Combine(Arma2OAPath, #"HardCorps.zip");
WebClient Download_Client = new WebClient();//Declaring the webclient as Download_Client
Download_Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);//the event handler
Download_Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);// " "
Download_Client.DownloadFileAsync(new Uri(HCDownloadURL.Trim().ToString()), HCZipPath);// " "
//extract
using (var zipFile = ZipFile.Read(HCZipPath))
{
zipFile.ExtractAll(Arma2OAPath, ExtractExistingFileAction.OverwriteSilently);
}
}
else
{
MessageBox.Show("Directory Validated!");
//Read users HardCorpsPath\version.txt and compare to server version.txt
//if server version > user version, download patch.zip where "patch" == the number version of the server's version.txt (ex: 1001.zip)
//On download complete, extract to HardCorpsPath and overwrite silently
}
}//close Download Button
and my ProgressChanged/Completed methods:
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
pbDownloader.Value = e.ProgressPercentage;//setting the progressbar value as downloadprogress
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
using (var zipFile = ZipFile.Read(String.Format(HCZipPath)))
{
zipFile.ExtractAll(Arma2OAPath, ExtractExistingFileAction.OverwriteSilently);
}
MessageBox.Show("Downloading Successful ", "Download_Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);//just a messagebox
pbDownloader.Value = (0);//resetting the progressbar
}
HCZipPath is a string variable (if that makes any difference)
In your btnDownload_Click method, you are trying to extract the file before it has been downloaded. You call Download_Client.DownloadFileAsync which starts the download, and you've correctly set up the handler for the DownloadFileCompleted event where you try to do the extraction (again). Take out the code below the DownloadFileAsync method call (to prevent the exception). You file is being extracted because you extract it in the Completed method (which is the correct way to do it).
I am wondering why when I write this in the URL:
http://ServerNameRedacted/IISHostedCalcService/FilesService.svc/GetFoldersAndFiles?selectedFolder=FOLDER//SUBFOLDER
I can't get the information in XML.
But when I use this, the parameter in my function which is exactly the same thing FOLDER//SUBFOLDER it doesn't work...
If I write it directly in a string it will work. So I don't know why, because the parameter is exactly the same...
Should I use string.format or something?
void listBoxFolders_Tap(object sender, GestureEventArgs e)
{
Folder directory = new Folder();
directory = (Folder)listBoxFolders.SelectedItem;
// Connexion to the webservice to get the subfolders and also the files
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadSubFoldersAndFiles);
wc.DownloadStringAsync(new Uri("http://myserver.net/IISHostedCalcService/FilesService.svc/GetFoldersAndFiles?selectedFolder=" + directory.FullPath.Substring(25) + '/'));
}
Considering that you're adding a forward slash at the end of the URI in your code, I would submit that they are not, in fact, the same.
Create your URI string outside of the DownloadStringAsync method, and use a a System.Diagnostics.Debug.WriteLine to see what the actual contents are of your URI string.
I wrote a program to download files from a website by using WebClient.DownloadFile().
public static void downWeb()
{
WebClient myWebClient = new WebClient();
path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (add() == 1)
{
Console.WriteLine("Response is " + add());
Console.WriteLine("Downloading File = " + dynFileName + "....");
myWebClient.DownloadFile(fullAddress, (path + dynFileName));
}
}
public static int add()
{
string url = fullAddress;
WebRequest webRequest = WebRequest.Create(url);
WebResponse webResponse;
try
{
webResponse = webRequest.GetResponse();
}
catch
{
return 0;
}
return 1;
}
downWeb() is a function to be called in the Main() function.
add() is a function that tests the availability of the file on server. If response is positive, it returns value "1".
fullAddress = address from where the files has to downloaded. It's changing every time before calling this function in a loop present in Main().
When I start my application, I ask the user to:
1) Enter URL to be downloaded i.e. www.1234.com\samplefiles\pg-1.pdf
2) Number of pages to be downloaded (By changing the above filename no. in a loop as rest of the url is same on server)
Now my problem is when I am downloading files, first file downloads PERFECTLY, but the second download is never finished. It says "REQUEST TIMED OUT", and my application closes.
I don't know what's happening here.
How can this be solved?
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
You must call the Close method to close the stream and release the connection. Failure to do so may cause your application to run out of connections.
Your problem likely is related to the fact that you do not dispose of your connections. You should make sure that you don't leak them.
I'm trying to load data into my Silverlight app. However, when it launches, I get a TargetInvocationException as soon as I hit e.Result:
public MainPage() {
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
wc.OpenReadAsync(new Uri("http://www.google.com"));
}
void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
Stream st = e.Result;
StreamReader sr = new StreamReader(st);
String result = sr.ReadToEnd();
}
Why does this fail, and what should I do to make it work?
PS, I'm afraid I cannot make a local proxy, because the app is going to be deployed as part of an app on an Apache Tomcat server, not an IIS.
Cheers
Nik
Silverlight cannot make cross-domain requests without a cross-domain policy file on the target domain. If you can't set up a proxy, you won't be able to get data from any domain other than the one hosting your application.