I have a small problem with downloading a file.
I have used windows Forms and need to download several files. They all are avaiable through a link that, when its opened automatically downloads the file.
I tried several things like WebCient or httpWebrequest but it all doesnt work.
Do you have any idea how i can launch this link without opening the browser every time and safe the file to a specific folder.
foreach (var doc in newDocs)
{
using (var wb = new WebClient())
{
MessageBox.Show("link" <- to cehck the if its the correct file;
HttpWebRequest request = WebRequest.Create("link") as HttpWebRequest;
wb.DownloadFile("link" <- 'link' cause its sensitive data.);
}
}
Hope it will help you.
void Download()
{
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadFileCompleted += Client_DownloadFileCompleted;
client.DownloadFileAsync(new Uri("url"), #"filepath");
}
}
private void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
//throw new NotImplementedException();
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//throw new NotImplementedException();
}
Related
I have problem when I try to create code for extracting .zip file into a folder, before I show you code, I want to tell you what I need to do?
Its simple, I want to write code so that when a user clicks on a button, it deletes a directory, and then downloads a new .zip file and extracts it at the same directory and name which was deleted... Its something like restoring directory to default form..
I successfully wrote code for deleting the directory and downloading .zip file but I cant write code for extracting that .zip ...
Here is the code
private void button2_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
var sprdir = new DirectoryInfo(#"cstrike/sprites");
string sprzippath = #"cstrike/sprites.zip";
string extzippath = #"cstrike";
if (!sprdir.Exists)
{
webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"), #"cstrike/sprites.zip");
}
else
{
sprdir.Attributes = sprdir.Attributes & ~FileAttributes.ReadOnly;
sprdir.Delete(true);
webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"), #"cstrike/sprites.zip");
}
}
And yea, I tried with using System.IO and System.IO.Compress and ZipFile.ExtractToDirectory and ExtractToDirectory, no one working... Just get red line below the text..
So first you need to add assembly System.IO.Compression.FileSystem into your projects.
Second thing is that you are using DownloadFileAsync which probably was not yet completed so your extraction fails (because no file exists yet)
The 3rd is that you are not creating the folder if it does not exists and that makes WebClient.DownloadFileAsync fail.
you need to register to the event where DownlodFileCompleted and to the extraction there.
here is an example:
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.IO.Compression;
namespace Stack
{
public partial class Form1 : Form
{
WebClient webClient;// = new WebClient();
const string basPath = #"D:\test";
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
//var sprdir = new DirectoryInfo(#"cstrike/sprites");
var sprdir = new DirectoryInfo(basPath);
string sprzippath = $"{basPath}/sprites.zip";
string extzippath = #"cstrike";
if (!sprdir.Exists)
{
Directory.CreateDirectory(basPath);
webClient = new WebClient();
webClient.DownloadFileCompleted += ExtratcZip;
webClient.DownloadFileAsync(
new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"),
$"{basPath}/sprites.zip");
}
else
{
sprdir.Attributes = sprdir.Attributes & ~FileAttributes.ReadOnly;
sprdir.Delete(true);
Directory.CreateDirectory(basPath);
webClient = new WebClient();
webClient.DownloadFileCompleted += ExtratcZip;
webClient.DownloadFileAsync(
new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"),
$"{basPath}/sprites.zip");
}
}
private void ExtratcZip(object sender, AsyncCompletedEventArgs e)
{
ZipFile.ExtractToDirectory($"{basPath}/sprites.zip", $"{basPath}");
}
}
}
hope it helps.
I'm brand new to coding with c# so can someone tell me how I can include code into this to show the progress bar of file downloading?
private void button4_Click(object sender, EventArgs e)
{
using (var client = new WebClient())
{
MessageBox.Show("File will start downloading");
var path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SOMEFILENAME.exe");
client.DownloadFile("GOOGLE DRIVE LINK", path);
MessageBox.Show("File has been downloaded!");
System.Diagnostics.Process.Start(path);
}
}
To update a progress bar while your WebClient downloads data you have to use a function that does this task in the background. WebClient has a useful function called DownloadFileAsync. This function does exactly that: It downloads in the background.
The code so with this change:
private void button4_Click(object sender, EventArgs e)
{
using (var client = new WebClient())
{
MessageBox.Show("File will start downloading");
var path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SOMEFILENAME.exe");
client.DownloadFileAsync(new Uri("GOOGLE DRIVE LINK"), path);
MessageBox.Show("File has been downloaded!");
System.Diagnostics.Process.Start(path);
}
}
Unfortunately we have a problem now. The method starts the download in the background and your code immediately continues. This means you press your button, the first MessageBox pops up, the second MessageBox pops up right after the first one and if your download isn't completed when you close the second one your file is executed too early.
To avoid this WebClient has events. The one we need is called DownloadFileCompleted. As the name suggests it executes whatever you want when the download is completed. So let's look at the new code:
string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SOMEFILENAME.exe"); // We need our path to be global
private void button4_Click(object sender, EventArgs e)
{
using (var client = new WebClient())
{
client.DownloadFileCompleted += client_DownloadFileCompleted; // Add our new event handler
MessageBox.Show("File will start downloading");
client.DownloadFileAsync(new Uri("GOOGLE DRIVE LINK"), path);
}
}
private void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) // This is our new method!
{
MessageBox.Show("File has been downloaded!");
System.Diagnostics.Process.Start(path);
}
Our next problem: client is inside a using block. This is great for foreground downloads but if we do it asynchronously (that's what doing it in the background is called) your client will be dead as soon as the block is left which is immediately after the download has been started. So let's make our client global to be able to destroy it later on.
string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SOMEFILENAME.exe");
WebClient client; // Here it is!
private void button4_Click(object sender, EventArgs e)
{
client = new WebClient(); // Create a new client here
client.DownloadFileCompleted += client_DownloadFileCompleted; // Add our new event handler
MessageBox.Show("File will start downloading");
client.DownloadFileAsync(new Uri("GOOGLE DRIVE LINK"), path);
}
private void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) // This is our new method!
{
MessageBox.Show("File has been downloaded!");
System.Diagnostics.Process.Start(path);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (client != null)
client.Dispose(); // We have to delete our client manually when we close the window or whenever you want
}
Now let's assume the user can press the button a second time before the download is completed. Our client would be overwritten then and the download would be canceled. So let's just ignore the button press if we're already downloading something and only create the new client if we don't have one. New code:
string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SOMEFILENAME.exe");
WebClient client;
private void button4_Click(object sender, EventArgs e)
{
if (client != null && client.IsBusy) // If the client is already downloading something we don't start a new download
return;
if (client == null) // We only create a new client if we don't already have one
{
client = new WebClient(); // Create a new client here
client.DownloadFileCompleted += client_DownloadFileCompleted; // Add our new event handler
}
MessageBox.Show("File will start downloading");
client.DownloadFileAsync(new Uri("GOOGLE DRIVE LINK"), path);
}
private void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) // This is our new method!
{
MessageBox.Show("File has been downloaded!");
System.Diagnostics.Process.Start(path);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (client != null)
client.Dispose(); // We have to delete our client manually when we close the window or whenever you want
}
Now that the boring part is done let's come to your problem: Viewing the progress in a progress bar. WebClient has got another event called DownloadProgressChanged. We can use it to update our progress bar.
Talking about progress bars: In Windows Forms you can create one by searching for ProgressBar in the tool bow window in Visual Studio. Then place it somewhere in your window. The ProgressBar component has a few properties which are important for its range. We're lucky, the default values are exactly what we need.
Our updated code (assuming your progress bar is called progressBar1:
string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SOMEFILENAME.exe");
WebClient client;
private void button4_Click(object sender, EventArgs e)
{
if (client != null && client.IsBusy) // If the client is already downloading something we don't start a new download
return;
if (client == null) // We only create a new client if we don't already have one
{
client = new WebClient(); // Create a new client here
client.DownloadFileCompleted += client_DownloadFileCompleted;
client.DownloadProgressChanged += client_DownloadProgressChanged; // Add new event handler for updating the progress bar
}
MessageBox.Show("File will start downloading");
client.DownloadFileAsync(new Uri("GOOGLE DRIVE LINK"), path);
}
private void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) // This is our new method!
{
MessageBox.Show("File has been downloaded!");
System.Diagnostics.Process.Start(path);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (client != null)
client.Dispose(); // We have to delete our client manually when we close the window or whenever you want
}
private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) // NEW
{
progressBar1.Value = e.ProgressPercentage;
}
Notes:
You can create the FormClosing method by double clicking the FormClosing event in your window's property box.
Calling client.Dispose() is only necessary when your program doesn't exit after closing the window. In any other case you could get rid of the FormClosing stuff completely.
That's all finally. I hope this wasn't too long for you and I could help you. Feel free to ask for clarification. That's what comments are there for.
I have this C# code that does not do the job. This code should run a code when the download is complete. But it does not work.
Code:
private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
ZipFile.ExtractToDirectory("web/data/main/web.zip", "web/");
}
private void flatToggle2_CheckedChanged(object sender)
{
if (flatToggle2.Checked)
{
//Create File
Directory.CreateDirectory("web/data/main/");
timer2.Start();
bunifuProgressBar1.Show();
bunifuCustomLabel1.Show();
//Downloand
using (var client = new WebClient())
{
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadFileCompleted);
client.DownloadFile("https://www.apachelounge.com/download/VC15/binaries/httpd-2.4.29-Win64-VC15.zip", "web/data/main/web.zip");
}
}
else
{
}
}
This is the code that does not work
private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
ZipFile.ExtractToDirectory("web/data/main/web.zip", "web/");
}
I tried to run this code without the Unzip but it did not work so I need help with this code.
Looking at the documentation, DownloadFile() is synchronous, so there is no callback needed. Try instead just:
using (var client = new WebClient())
{
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadFileCompleted);
client.DownloadFile("https://www.apachelounge.com/download/VC15/binaries/httpd-2.4.29-Win64-VC15.zip", "web/data/main/web.zip");
ZipFile.ExtractToDirectory("web/data/main/web.zip", "web/");
}
This should suffice.
I am trying to make a download tool for a project of mine (In C#).
How ever, the users should be able to set a download folder by themselves using folderBrowserDialog1.SelectedPath.
Currently I am downloading like this:
private void button1_Click(object sender, EventArgs e)
{
String Pfad = TextBox1.Text;
WebClient Client = new WebClient();
Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);
Client.DownloadFileAsync(new Uri("http://dl.4players.de/ts/releases/3.0.13.6/teamspeak3-server_win64-3.0.13.6.zip"), Pfad);
}
As you can see the users have to type in the path, but it should be selectable via folderBrowserDialog1.SelectedPath.
thanks!
I'm not sure what you're stuck on, you've correctly identified that a FolderBrowserDialog would be a good tool to use.
private void button1_Click(object sender, EventArgs e)
{
// Shows the FolderBrowserDialog and prevents further actions until a choice is made
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK) // Checks they selected a path
{
string Pfad = folderBrowserDialog1.SelectedPath;
WebClient Client = new WebClient();
Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);
Client.DownloadFileAsync(new Uri("http://dl.4players.de/ts/releases/3.0.13.6/teamspeak3-server_win64-3.0.13.6.zip"), Pfad);
}
}
Well, Im trying to donwload a file from GitHub using WebClient C# Class but I always get the file corrupted.. this is my code
using (var client = new WebClient())
{
client.DownloadFile("https://github.com/trapped/rotmg_svr/archive/master.zip", #"C:/Users/Asus/Desktop/aa.zip");
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
}
static void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine(e.ProgressPercentage.ToString());
}
//////
public static void ReadFile()
{
WebClient client = new WebClient();
client.DownloadFile("https://github.com/trapped/rotmg_svr/archive/master.zip", #"C:/Users/Asus/Desktop/aa.zip");
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
}
static void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
Console.WriteLine("Finish");
}
static void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.WriteLine(e.ProgressPercentage);
}
Now Im using that code and calling that function Reader.ReadFile(); , file downloads good but nothing is written in console (e.percentage) .
Thanks
You are calling DownloadFile() before setting up your event handlers. The call to DownloadFile() will block your thread until the file has finished downloading, which means those event handlers will not be attached before your file has already downloaded.
You could switch the order around like so:
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFile("https://github.com/trapped/rotmg_svr/archive/master.zip", #"C:/Users/Asus/Desktop/aa.zip");
or you could use DownloadFileAsync() instead, which will not block your calling thread.