When I use:
WebClient web = new WebClient();
web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChangedWeb);
web.DownloadFileAsync(new Uri("http://www.website.com/Webs.exe"),
Environment.SpecialFolder.Desktop + #"\Webs.exe");
...Nothing downloads.
But if i change it to"
WebClient web = new WebClient();
web.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChangedWeb);
web.DownloadFileAsync(new Uri("http://www.website.com/Webs.exe"),
Environment.SpecialFolder.Desktop + "Webs.exe");
Then It downloads, but I get a file named "desktopWebs.exe". So How can I save a file to the desktop?
Thanks
What you want is this...
Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\Webs.exe";
Otherwise you are just tacking on the word desktop instead of the actual path.
You can use Path.Combine
web.DownloadFileAsync(new Uri("http://www.website.com/Webs.exe"),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Webs.exe"));
This function will automatically insert (or remove) slashes as well as adapt to any file system being used
You should also consider using Environment.SpecialFolder.DesktopDirectory, this points to the actual physical location of the desktop folder on the disk.
Related
I am trying to download a file using webclient method DownloadFile But its giving me error that
The process cannot access the file '...\d915877c-cb7c-4eeb-97d8-41d49b75aa27.docx' because it is being used by another process.
But when I open the file by clicking it, it opening.
There are same question requesting same info but none are accepted answers.
any help will be appreciated
It may be oS that is not letting file go. Whatever it is but after searching a lot I am unable to find solution
Here is the code to create a file
Document d = new Document();
d.Save(HttpContext.Current.Server.MapPath(#"Invoice\" + iname + ".docx"));
I am using aspose word dll
and following way I am accessing it
using (var client = new System.Net.WebClient())
{
client.UseDefaultCredentials = true;
client.DownloadFile(Server.MapPath("invoice/" + Request.QueryString["id"].ToString() + ".docx"),Server.MapPath("invoice/" +Request.QueryString["id"].ToString() + ".docx"));
client.Dispose();
}
and BTW its giving same error even to files that are not creaated using code.
Give a different path where to save the download file which is different from the download source path. If you want to replace the file do it after disposing the webclient by using File.replace() method.
string downloadPath = "Your download path";
string destinationPath = "the path where the file should be saved";`//this should be different from "download path"
File.Download(downloadPath,destinationPath);
I use a website to get stats on wifi usage. The website creates an image of a graph representation of the data. The way it does this is by the user, setting a date. So for example, lets say it was last months statistics. The website generates a URL which is then sent to the server and the server returns an image. an examples of the link is like this:
https://www.example.com/graph/daily_usage?time_from=2015-06-01+00%3A00%3A00+%2B0100&time_to=2015-06-30+23%3A59%3A59+%2B0100&tsp=1436519988
The problem is, I am making a third party program that will download this image to be used in my program. However, I cannot use the file. It is as if the file is corrupt or something. I have tried a few methods but maybe someone can suggest a different approach. Basically, how do I download an image that is generated by a server from a URL link?
P.S.
Just noticed that if I download the file by right clicking through a browser and save, the image downloads with a size of 17.something kilobytes. But if I use the WebClient method to download the image, it only downloads 1.5kb. Why would that be? Seems like the WebClient method does not download completely.
Currently my code
if (hrefAtt == "Usage Graph")
{
string url = element.getAttribute("src");
WebClient client = new WebClient();
client.DownloadFile(url, tempFolderPath + "\\" + currentAcc + "_UsageSummary.png");
wd.AddImagesToDoc(tempFolderPath + "\\" + currentAcc + "_UsageSummary.png");
wd.SaveDocument();
}
TempFolderPath is my desktop\TempFolder\
UPDATE
Out of random, I decided to see the raw data of the file with notepad and interestingly, the image data was actually a copy of the websites homepage html code, not the raw data of the image :S how does that make sense?
This will download the Google logo:
var img = Bitmap.FromStream(new MemoryStream(new WebClient().DownloadData("https://www.google.co.uk/images/srpr/logo11w.png")));
First of all, you have to understand link texture. If all links are same or close to each other, you have to use substring/remove/datetime etc. methods to make your new request link. For example;
string today = DateTime.Now.ToShortDateString();
string generatedLink = #"http://www.yoururl.com/image + " + today + ".jpg";
string generatedFileName = #"C:\Usage\usage + " + today + ".jpg";
WebClient wClient = new WebClient();
wClient.DownloadFile(generatedLink, generatedFileName);
i deployed a website on IIS running on localhost/xxx/xxx.aspx . On my WPF side , i download a textfile using webclient from the localhost server and save it at my wpf app folder
this is how i do it :
protected void DownloadData(string strFileUrlToDownload)
{
WebClient client = new WebClient();
byte[] myDataBuffer = client.DownloadData(strFileUrlToDownload);
MemoryStream storeStream = new MemoryStream();
storeStream.SetLength(myDataBuffer.Length);
storeStream.Write(myDataBuffer, 0 , (int)storeStream.Length);
storeStream.Flush();
string currentpath = System.IO.Directory.GetCurrentDirectory() + #"\Folder";
using (FileStream file = new FileStream(currentpath, FileMode.Create, System.IO.FileAccess.ReadWrite))
{
byte[] bytes = new byte[storeStream.Length];
storeStream.Read(bytes, 0, (int)storeStream.Length);
file.Write(myDataBuffer, 0, (int)storeStream.Length);
storeStream.Close();
}
//The below Getstring method to get data in raw format and manipulate it as per requirement
string download = Encoding.ASCII.GetString(myDataBuffer);
}
This is by writing btyes and saving them . But how do i download multiple image files and save it on my WPF app folder? I have a URL like this localhost/websitename/folder/designs/ , under this URL , there is many images , how do i download all of them ? and save it on WPF app folder?
Basically i want to download the contents of the folder whereby the contents are actually images.
First, the WebClient class already has a method for this. Use something like client.DownloadFile(remoteUrl, localFilePath).
See this link:
WebClient.DownloadFile Method (String, String)
Secondly, you will need to index the files you want to download on the server somehow. You can't just get a directory listing over HTTP and then loop through it. The web server will need to be configured to enable directory listing, or you will need a page to generate a directory listing. Then you will need to download the results of that page as a string using WebClient.DownloadString and parse it. A simple solution would be an aspx page that outputs a plaintext list of files in the directory you want to download.
Finally, in the code you posted you're saving every single file you download as a file named "Folder". You need to generate a unique filename for each file you want to download. When you're looping through the files you want to download, use something like:
string localFilePath = Path.Combine("MyDownloadFolder", imageName);
where imageName is a unique filename (with file extension) for that file.
I'm using a webview to display certain data in my windows 8 app. I would like to user an include to a local js file as well as use locally stored images.
Is this possible?
I haven't had any luck by putting the local path where the files are located.
According to WebView documentation you can only reference other files using the ms-appx-web protocol, i.e. to load the files stored in Windows.ApplicationModel.Package.Current.InstalledLocation, meaning that they need to be distributed as content along with your application. The control doesn't support ms-appdata protocol for security reasons, i.e. you can't open files stored Windows.Storage.ApplicationData.Current.LocalFolder Windows.Storage.ApplicationData.Current.RemoteFolder or Windows.Storage.ApplicationData.Current.TempFolder where you'd need to put them if you were generating or downloading them at runtime.
In JavaScript apps WebView is a bit more flexible: it does support ms-appdata protocol as well, but only for media files such as images. It cannot open any potentially executable code, such as script or CSS.
If you want to open some local .html file or atc. you should download it in InstalledLocation folder. If you haven't option to create a new file you can just use file.CopyAsync(htmlFolder, fname + ".html");
For example I create some .html file:
StorageFolder htmlFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFolderAsync(#"HtmlFiles", CreationCollisionOption.GenerateUniqueName);
IStorageFile file = await htmlFolder .CreateFileAsync(fname + ".html", CreationCollisionOption.GenerateUniqueName);
and than I can easily open this .html file with or without FileOpenPicker:
var fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".html");
var file = await fop.PickSingleFileAsync();
if (file != null)
{
string myPath = file.Path.Substring(file.Path.IndexOf("HtmlFiles"));
myWebview.Navigate(new Uri("ms-appx-web:///" + myPath));
}
And don't forget - just only from InstalledLocation you can open it with ms-appx-web:///
If the WebView is IE10 based, FIleReader may be what you are looking for. Here is a snippet of code that I use on an image ipload page to show images in a page when they are selected via a File Open dialog:
$('input:file').each(function(index, evt){
if(index===0)
{
var files = evt.files;
for(var i=0;i<files.length;i++)
{
if(files[i].name===filename)
{
var reader = new FileReader();
reader.onload=(function(theFile){
return function(e){
var line= uploader.fineUploader('getItemByFileId',id);
if(line!=undefined)
$(line).append('<img class="fileimage" id="fileImage-' + id + '" src="'+e.target.result+'" />');
};
})(files[i]);
reader.readAsDataURL(files[i]);
break;
}
}
}
I hope this points you in the right direction!
I know a few similar questions have been asked on how to download files using WebClient. I can download individual files perfectly fine, but I want to download a range of files. Anywhere from 1-6000 files. I can download them just fine into my current directory, but I am stumped on how to download them to a different directory based upon where they're being downloaded from. Do I need to temporarily change the current working directory just before downloading them?
And slightly on the same topic, I'm stuck on how to verify the files exist before downloading them. I don't want to waste bandwidth or diskspace with empty files.. Here's what I have so far:
for (int x = 1; x <= 6000; x++)
{
pbsscount = x.ToString();
// Used for downloading file
string directoryName = textBox1.Text.ToString().Replace(":", "_");
if (!Directory.Exists(textBox1.Text))
Directory.CreateDirectory(directoryName.Substring(7));
string wholePBSSurl = textBox1.Text + "/" + "pb" + pbsscount.PadLeft(6, '0') + ".png";
// Used for saving file, file name in directory
string partPBSSurl = "pb" + pbsscount.PadLeft(6, '0') + ".png";
Uri uri2 = new Uri(wholePBSSurl);
//if (fileExists(wholePBSSurl))
//{
// Initialize downloading info, grab progressbar info
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
// Save file to folder
//webClient.DownloadFileAsync(uri2, textBox1.Text + "/" + partPBSSurl);
webClient.DownloadFileAsync(uri2, partPBSSurl);
//}
}
Do I need to temporarily change the current working directory just before downloading them?
The second parameter can be a full path #"C:\folder\file.png". If you're fine with relative path to your current directory, just change the code to webClient.DownloadFileAsync(uri2, directoryName + partPBSSurl); or even better use System.Path.Combine(directoryName, partPBSSurl)
Sure you can know the size before If sever supports that. See: How to get the file size from http headers
I don't want to waste bandwidth or diskspace with empty files.
I wouldn't worry about that. The performance slow down is negligible.
There is no need to change the current directory. You are already using an overload of DownloadFileAsync that accepts a file path as the second parameter.
Just ensure that partPBSSurl contains a full path to the destination file, including both the directory and filename.
With regard to your second question of avoiding wasted time if the file does not exist, it so happens that I asked the same question recently:
Fail Fast with WebClient
Finally, I recently extended WebClient to provide simpler progress change events and allow for the timeout to be changed. I posed that code here:
https://stackoverflow.com/a/9763976/141172