Download a file from a Variable URL c# - c#

We have been requested to go and Download an order file from our customers site via a url.
I want to do something like this.
string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
}
But the URL will be variable as we have to specify the Date and Time within the URL we post.
And the File we download will be variable also.
As I'm new to C# I would like some advise as to how to achieve this?
Thanks In Advance

It depends on how the URLs will be generated. Do they follow a pattern? Do you know them in advance?
private void GetVariableFile(string remoteUri, string filename) {
string myStringWebResource = null;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient()) {
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
//Do stuffs
}
}
You might wanna pass the Uri & the file obtained to a method which will handle the download and the elaboration, or in case you need to return the result, change the return type so that it can return the info you need.

Related

How Can I get the real name of an image from a url

I have the next url about an image:
https://i.discogs.com/HE17wcv1sG6NDK1WcVyoQjSqUGDZva3SYvm6vXoCMOo/rs:fit/g:sm/q:90/h:600/w:600/czM6Ly9kaXNjb2dz/LWRhdGFiYXNlLWlt/YWdlcy9SLTk2OTY5/NjktMTQ4NDkzNzkw/Ni00MDcyLmpwZWc.jpeg
If I open the url with the navigator and then I press de right button to save this image in my hard disc the name solved by the navigator for this file image is distinct.
How can i get the last name of the file in c#?
If you're set on using WebClient then you can download the data into memory, check for the Content-Disposition header, and then change the filename accordingly. I've added commented out parts that you can use instead of their synchronous counterparts if you're using this method asynchronously.
// private static async Task DownloadImageAsync(string url, string folder)
private static void DownloadImage(string url, string folder)
{
var uri = new Uri(url);
string fileName = Path.GetFileName(uri.AbsolutePath);
WebClient client = new WebClient();
// byte[] fileData = await client.DownloadDataTaskAsync(url);
byte[] fileData = client.DownloadData(url);
string disposition = client.ResponseHeaders.Get("Content-Disposition"); // try to get the disposition
if (!string.IsNullOrEmpty(disposition) // check it has a value
&& ContentDispositionHeaderValue.TryParse(disposition, out var parsedDisposition) // check it can be parsed
&& !string.IsNullOrEmpty(parsedDisposition.FileName)) // check a filename is specified
{
fileName = parsedDisposition.FileName.Trim('"'); // replace the normal filename with the parsed one
}
// await File.WriteAllBytesAsync(Path.Combine(folder, fileName), fileData);
File.WriteAllBytes(Path.Combine(folder, fileName), fileData);
}
Usage: DownloadImage(myurl, #"C:\Users\Me\Desktop");
That said, WebClient is a bit old-fashioned and you should probably use HttpClient for newer developments:
private static async Task DownloadImageAsync(string url, string folder)
{
var uri = new Uri(url);
string fileName = Path.GetFileName(uri.AbsolutePath);
using var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
if (!string.IsNullOrEmpty(response.Content.Headers.ContentDisposition?.FileName))
{
fileName = response.Content.Headers.ContentDisposition.FileName.Trim('"');
}
using var outputFile = File.Create(Path.Combine(folder, fileName));
await response.Content.CopyToAsync(outputFile);
}
Usage: await DownloadImageAsync(myurl, #"C:\Users\Me\Desktop");
Microsoft recommend using a single static instance of HttpClient throughout your application (docs). This does have pitfalls though, so depending on your application, you might want to look into using IHttpClientFactory, which works to solve the issues that come from using a static HttpClient.

Uploading and downloading small files to a cloud drive in-game? (Unity3D)

I need any player's client to be able to upload and download files (they are text files that have replay data. I'm making a racing game and want players to be able to send and download replays.) while in-game. I'm trying to use Dropbox but I'm having problems. I'm open to other file hosting services but I don't really know how to send and get data from them. I keep making little changes here and there and they all give me different errors. Is there anything I'm doing blatantly wrong here? I'm expecting the main problem to be in the dropbox URL I'm using. Here's what my code looks like:
private void DownloadReplay()
{
string l_playerID = PlayFabManager.load_PlayfabId;
string l_levelID = PlayFabManager.load_levelID;
using (WebClient wc = new WebClient())
{
string path = Path.Combine(Application.persistentDataPath, $"{l_playerID}{l_levelID}.replay");
string url = ("https://www.dropbox.com/s/f786vep0z9yd11s/"+ $"{l_playerID}{l_levelID}");
wc.Credentials = new NetworkCredential("xx", "xx");
wc.DownloadFile((new System.Uri(url)), path);
}
}
private void UploadReplay()
{
string s_playerID = PlayFabManager.load_PlayfabId;
string s_levelID = PlayFabManager.load_levelID;
using (WebClient client = new WebClient())
{
string path = Path.Combine(Application.persistentDataPath, $"{s_playerID}{s_levelID}.replay");
string url = Path.Combine("https://www.dropbox.com/s/f786vep0z9yd11s/" + $"{s_playerID}{s_levelID}");
client.Credentials = new NetworkCredential("xx", "xx");
client.UploadFile(url, path);
}
}
Right now this one gives me an error 404, even though the file matching the string is in my dropbox.

Copy file from URI format path to local path

I am trying to copy a file which is on a server and all I've got is it's URI format path.
I've been trying to implement copying in C# .NET 4.5, but seems like CopyFile is not good with handling URI formats.
So I've used IronPython with shutil, but seems like it is also not good with URI format paths.
How do I get that file local?
private string CopyFile(string from, string to, string pythonLibDir, string date)
{
var dateTime = DateTime.Today;
if (dateTime.ToString("yy-MM-dd") == date)
{
return "";
}
var pyEngine = Python.CreateEngine();
var paths = pyEngine.GetSearchPaths();
paths.Add(pythonLibDir);
pyEngine.SetSearchPaths(paths);
pyEngine.Execute("import shutil\n" +
"shutil.copyfile('" + from + "', '" + to + "')");
return dateTime.ToString("yy-MM-dd");
}
I take all paths from xml config file.
you can use a webclient and then get the file on a particular folder.
using (WebClient wc = new WebClient())
wc.DownloadFile("http://sitec.com/web/myfile.jpg", #"c:\images\xyz.jpg");
or you can also use: HttpWebRequest inc ase you just want to read the content from a file from a server.
var http = (HttpWebRequest)WebRequest.Create("http://sitetocheck.com");
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
With Python
import urllib
urllib.urlretrieve("http://www.myserver.com/myfile", "myfile.txt")
urlretrieve
Copy a network object denoted by a URL to a local file, if necessary. If the URL points to a local file, or a valid cached copy of the object exists, the object is not copied.

Downloading mp3 files directly

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);
});

Save file to location?

I am downloading a file off a website and it always saves into my Download files, is there a way where i can select where to save the file to?
public void myDownloadfile(string token, string fileid, string platform)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("Token", token);
parameters.Add("fileid", fileid);
parameters.Add("plateform", platform);
string url;
url = "https://formbase.formmobi.com/dvuapi/downloadfile.aspx?" + "token=" + token + "&fileid=" + fileid + "&platform=" + platform;
System.Diagnostics.Process.Start(url);
}
System.Diagnostics.Process.Start just opens your default web browsers on the required url.
You can set your browser to open save as dialog.
But better use WebClient.DownloadFile: http://msdn.microsoft.com/en-us/library/ez801hhe.aspx
It receives the path of the target file as one of it's parameters.
Since you are downloading the file using your system's standard browser, you have to change the setting there.
Otherwise, you probably want to use the WebClient class to download a file, since it is as easy to use as
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", #"c:\myfile.txt");
(example from here)
Don't use Process.Start that will launch the default browser to download the file and the download location will be very dependent on the users system settings. Use WebClient to download it instead and it will be easier to specify a location.
public void myDownloadfile(string token, string fileid, string platform)
{
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("Token", token);
parameters.Add("fileid", fileid);
parameters.Add("plateform", platform);
string url;
url = "https://formbase.formmobi.com/dvuapi/downloadfile.aspx?" + "token=" + token + "&fileid=" + fileid + "&platform=" + platform;
System.Net.WebClient wc = new System.Net.WebClient()
wc.DownloadFile(url, "C:\\myFile.ext")
}
You can use WebClient to download the data and use SaveFile Dialog to set the default location where you which to start.
http://www.techrepublic.com/blog/programming-and-development/download-files-over-the-web-with-nets-webclient-class/695
You can use HttpResponse.
Go through the link: prompt a save dialog box to download a file

Categories