I have a web service, like this example for downloading a zip file from the server. When i open the URL through web browsers,I can download the zip file correctly. The problem is when I try to download the zip file through my desktop application. I use the following code to download:
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri(#"http://localhost:9000/api/file/GetFile?filename=myPackage.zip"), #"myPackage.zip");
After testing this, I get the myPackage.zip downloaded, but it is empty, 0kb. Any help about this or any other server code + client code example?
You can try to use HttpClient instead. Usually, it is more convenient.
var client = new HttpClient();
var response = await client.GetAsync(#"http://localhost:9000/api/file/GetFile?filename=myPackage.zip");
using (var stream = await response.Content.ReadAsStreamAsync())
{
var fileInfo = new FileInfo("myPackage.zip");
using (var fileStream = fileInfo.OpenWrite())
{
await stream.CopyToAsync(fileStream);
}
}
Related
I want to get a link from a TextBox and download a file from link.
But before downloading file, I want to know the size of the file in advance and create an empty file with that size. but I can't.
and another question, I want to show percentage of download progress. How can I know data is downloaded and I should update the percentage?
WebRequest request = WebRequest.Create(URL);
WebResponse response = request.GetResponse();
totalSize = request.ContentLength;//always is -1
using (FileStream f = new FileStream(savePath, FileMode.Create))
{
f.SetLength(totalSize);
}
System.IO.StreamReader reader = new
System.IO.StreamReader(response.GetResponseStream());
WebClient client = new WebClient();
client.DownloadFile (URL, savePath);
The best way would be to use the WebClient with its DownloadFile Function, which has an async callback for events like Completed or ProgressChanged.
Getting the size of the file in advance would be a step harder though.
I use C# windows form app and I want to download content website and after edit it display in external browser.
WebClient client = new WebClient();
string s = client.DownloadString("http://google.com");
How can i display String html (s) in external browser?
Regard.
WebClient client = new WebClient();
string s = client.DownloadString("http://google.com");
Process.Start("http://www.google.com");
If you want make it complex a little more, you can save it to a local file and open it in external browser by Process.Start() function.
WebClient client = new WebClient();
string s = client.DownloadString("http://google.com");
StreamWriter sw = File.CreateText("google.html");
sw.Write(s);
sw.Close();
Process.Start("google.html");
I have struggle with downloading few MB excel file from URL and then work with it. Im using VS2010 so i cant use await keyword.
My code follows:
using (WebClient webClient = new WebClient())
{
// setting Windows Authentication
webClient.UseDefaultCredentials = true;
// event fired ExcelToCsv after file is downloaded
webClient.DownloadFileCompleted += (sender, e) => ExcelToCsv(fileName);
// start download
webClient.DownloadFileAsync(new Uri("http://serverx/something/Export.ashx"), exportPath);
}
The line in ExcelToCsv() method
using (FileStream stream = new FileStream(filePath, FileMode.Open))
Throws me an error:
System.IO.IOException: The process cannot access the file because it
is being used by another process.
I tried webClient.DownloadFile() only without an event but it throws same error. Same error is throwed if i do not dispose too. What can i do ?
Temporary workaround may be Sleep() method but its not bullet proof.
Thank you
EDIT:
I tried second approach with standard handling but i have mistake in the code
using (WebClient webClient = new WebClient())
{
// nastaveni ze webClient ma pouzit Windows Authentication
webClient.UseDefaultCredentials = true;
// <--- I HAVE CONVERT ASYNC ERROR IN THIS LINE
webClient.DownloadFileCompleted += new DownloadDataCompletedEventHandler(HandleDownloadDataCompleted);
// spusteni stahovani
webClient.DownloadFile(new Uri("http://czprga2001/Logio_ZelenyKyblik/Export.ashx"), TempDirectory + PSFileName);
}
public delegate void DownloadDataCompletedEventHandler(string fileName);
public event DownloadDataCompletedEventHandler DownloadDataCompleted;
static void HandleDownloadDataCompleted(string fileName)
{
ExcelToCsv(fileName);
}
EDIT: approach 3
I tried this code
while (true)
{
if (isFileLocked(downloadedFile))
{
System.Threading.Thread.Sleep(5000); //wait 5s
ExcelToCsv(fileName);
break;
}
}
and it seems that it is never accessible :/ I dont get it.
Try to use DownloadFile instead of DownloadFileAsync, as you do in Edit 1, like this:
string filename=Path.Combine(TempDirectory, PSFileName);
using (WebClient webClient = new WebClient())
{
// nastaveni ze webClient ma pouzit Windows Authentication
webClient.UseDefaultCredentials = true;
// spusteni stahovani
webClient.DownloadFile(new Uri("http://czprga2001/Logio_ZelenyKyblik/Export.ashx"), filename);
}
ExcelToCsv(filename); //No need to create the event handler if it is not async
From your example it seems that you do not need asynchronous download, so use synchronous download and avoid possible related problems like here.
Also use Path.Combine to combine parts of a path like folder and filename.
There is also a chance that it is locked by something else, use Sysinternals Process Explorer's Find DLL or Handle function to check it.
Use local disk to store downloaded file to prevent problems with network.
I'm trying to download files from my FTP server - multiples at the same time. When i use the DownloadFileAsync .. random files are returned with a byte[] Length of 0. I can 100% confirm the file exists on the server and has content AND there FTP server (running Filezilla Server) isn't erroring and say's the file has been transferred.
private async Task<IList<FtpDataResult>> DownloadFileAsync(FtpFileName ftpFileName)
{
var address = new Uri(string.Format("ftp://{0}{1}", _server, ftpFileName.FullName));
var webClient = new WebClient
{
Credentials = new NetworkCredential(_username, _password)
};
var bytes = await webClient.DownloadDataTaskAsync(address);
using (var stream = new MemoryStream(bytes))
{
// extract the stream data (either files in a zip OR a file);
return result;
}
}
When I try this code, it's slower (of course) but all the files have content.
private async Task<IList<FtpDataResult>> DownloadFileAsync(FtpFileName ftpFileName)
{
var address = new Uri(string.Format("ftp://{0}{1}", _server, ftpFileName.FullName));
var webClient = new WebClient
{
Credentials = new NetworkCredential(_username, _password)
};
// NOTICE: I've removed the AWAIT and a different method.
var bytes = webClient.DownloadData(address);
using (var stream = new MemoryStream(bytes))
{
// extract the stream data (either files in a zip OR a file);
return result;
}
}
Can anyone see what I'm doing wrong, please? Why would the DownloadFileAsync be randomly returning zero bytes?
Try out FtpWebRequest/FtpWebResponse classes. You have more available to you for debugging purposes.
FtpWebRequest - http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.110).aspx
FtpWebResponse - http://msdn.microsoft.com/en-us/library/system.net.ftpwebresponse(v=vs.110).aspx
Take a look at http://netftp.codeplex.com/. It appears as though almost all methods implement IAsyncResult. There isn't much documentation on how to get started, but I would assume that it is similar to the synchronous FTP classes from the .NET framework. You can install the nuget package here: https://www.nuget.org/packages/System.Net.FtpClient/
I've been using xamarin for a while and the current project I'm working on will require some mp3 files to be downloaded.
I saw tutorials for downloading a file and downloading an image, but they didn't lead me anywhere and are for iOS.
Given a url www.xyz.com/music.mp3, how do I download the mp3 file and save it?
Simplest way is to use WebClient and if on the UI thread then call method DownloadFileTaskAsync:
button.Click += async delegate
{
var destination = Path.Combine(
System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ApplicationData),
"music.mp3");
await new WebClient().DownloadFileTaskAsync(
new Uri("http://www.xyz.com/music.mp3"),
destination);
};
Xamarin.iOS Docs converted to download bytes
The Xamarin.iOS docs WebClient sample for downloading a file should work just fine after you tweak from downloading a string to downloading bytes (note DownloadDataAsync and DownloadDataCompleted vs String sibling functions).
var webClient = new WebClient();
webClient.DownloadDataCompleted += (s, e) => {
var text = e.Result; // get the downloaded text
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = "downloaded.mp3";
string localPath = Path.Combine (documentsPath, localFilename);
File.WriteAllText (localpath, text); // writes to local storage
};
var url = new Uri("http://url.to.some/file.mp3"); // give this an actual URI to an MP3
webClient.DownloadDataAsync(url);
Using HttpClient
If you want to use the newer HttpClient library. Add a reference to System.Net.Http to your Xamarin.Android project and give something like this a shot.
var url = new Uri("http://url.to.some/file.mp3");
var httpClient = new HttpClient ();
httpClient.GetByteArrayAsync(url).ContinueWith(data => {
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = "downloaded.mp3";
string localPath = Path.Combine (documentsPath, localFilename);
File.WriteAllBytes (localPath, data.Result);
});