How to handle URL having no specific suffix - c#

My Code for Downloader uses two textboxes :
Two get user URL
To specify the drive
private void downloadbtn_Click(object sender, EventArgs e)
{
WebClient myWebClient = new WebClient();
//Declarations for string objects
string downloadURL, path;
//raw URL taken from user
downloadURL = this.downloadURL.Text;
path = savePath.Text;
Uri tmp = new Uri(downloadURL);
string EndPathFileName = tmp.Segments.Last();
path = path + #"\" + EndPathFileName;
//downloads file using async method
myWebClient.DownloadFileAsync(tmp, savePath.Text);
}
The issue arises when i use URL of type:
http://www.dailymotion.com/video/x1coxfe_aryan-khan-tera-pyar-official-music-video-hd_music
which didn't have any suffix i.e. mp3,mp4 etc.
Here it downloads an icon of zero data in the winkle of eye as compared to url having *.mp3/4 etc
Any suggestions please

You should check the Content-Type header not the URL to know the type of file. You can read the content-type like this
string type = client.ResponseHeaders["content-type"];

Related

Using c#, ios to get a JSON address from an API

I am trying to make for example a simple weather app. Mine is for an Air Quality API.
I had this code but I didn't think it would work with JSON.
var webClient = new WebClient();
...
var text = e.Result; // get the downloaded text and store in this variable
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = "downloaded.txt"; // local file to save text in
string localPath = Path.Combine(documentsPath, localFilename); // local path to save file to
File.WriteAllText(localPath, text); // writes to local storage
myTextView.Text = text; // updates the TextView element on the screen with downloaded text data
Then Just
var url = new Uri("https://api.breezometer.com/baqi/?lat=" + latitude + "&lon=" + longitude +"&key=YOUR KEY HERE");
webClient.Encoding = Encoding.UTF8;
webClient.DownloadStringAsync(url);
Im just not sure of the encoding method for JSON.
If anyone knows please answer thanks...
Use the WebClient class in System.Net:
var json = new WebClient().DownloadString("url");
Origin answer:
How to get a json string from url?

Downloading Large Google Drive files with WebClient in C#

I know there are tones of questions on this subject already. After reading all the threads, I decided to get a redirected URL in a confirmation HTML page and then use it as a direct link to download.
As you know, the original URL format of the direct download link is like this.
https://drive.google.com/uc?export=download&id=XXXXX..
But if the size of the target file is big, then it is like this.
https://drive.google.com/uc?export=download&confirm=RRRR&id=XXXXX..
I can get RRRR from the first downloaded data, so I need to try twice in order to download the real file. The concept is very simple enough but I can't get this to work.
class Test
{
class MyWebClient: WebClient
{
CookieContainer c = new CookieContainer();
protected override WebRequest GetWebRequest(Uri u)
{
var r = (HttpWebRequest) base.GetWebRequest(u);
r.CookieContainer = c;
return r;
}
}
static string GetRealURL(string filename)
{
// Some Jobs to Parse....
return directLink;
}
static void Main()
{
MyWebClient wc = new MyWebClient();
string targetLink = "https://drive.google.com/uc?export=download&id=XXXXXXX";
wc.DownloadFile(targetLink, "tempFile.tmp");
targetLink = GetRealURL("tempFile.tmp");
wc.DownloadFile(targetLink, "realFile.dat");
}
}
What did I wrong?
I can get the right download link from the first file, but I get another confirmation page file with another confirm code on the second try. I thought this was because of cookies, so I created my own WebClient class as you can see above.
Also I originally used DownloadFileAsync(), and changed it to DownloadFile() just in case, but the same result..
I'm still thinking it has something to do with cookie things.
What am I missing here?
I had this same problem but had solved it in an HttpClient. I tried via your approach with WebClient and was able to get it to work. You don't show your GetRealUrl() source, but i'm willing to bet in there lies the issue. Here's how I did it:
You need to parse the html response to get the url in the href attribute of the "download anyway" button. It will only have the relative url, (the /uc?export=download... part)
You need to replace the xml escape character & with &
Then you can build the url using thte domain https://drive.google.com
At which point you can download the file. Here's the source (used in a test WPF application):
class MyWebClient : WebClient
{
CookieContainer c = new CookieContainer();
protected override WebRequest GetWebRequest(Uri u)
{
var r = (HttpWebRequest)base.GetWebRequest(u);
r.CookieContainer = c;
return r;
}
}
private async void WebClientTestButtonGdrive_Click(object sender, RoutedEventArgs e)
{
using (MyWebClient client = new MyWebClient())
{
//get the warning page
string htmlPage = await client.DownloadStringTaskAsync("https://drive.google.com/uc?id=XXXXXXX&export=download");
//use HtmlAgilityPack to get the url with the confirm parameter in the url
HtmlDocument document = new HtmlDocument();
document.LoadHtml(htmlPage);
HtmlNode node = document.DocumentNode;
HtmlNode urlNode = node.SelectSingleNode(#"//a[contains(#href, 'XXXXXXX') and contains(#id, 'uc-download-link')]//#href");
string downloadUrl = urlNode.Attributes["href"].Value;
downloadUrl = downloadUrl.Replace("&", "&");
downloadUrl = "https://drive.google.com" + downloadUrl;
//download the file
if (File.Exists("FileToDownload.zip"))
File.Delete("FileToDownload.zip");
await client.DownloadFileTaskAsync(downloadUrl, "FileToDownload.zip");
}
}

How to download file in C# with its name?

I'm trying to download file from URL using WebClient, the problem is that the function .DownloadFile() requiring URL, and name that will be given to the saved file, but when we access to the URL it already has the file name.
How can I keep the file name as it is in the URL?
This should work if I understand your question correctly:
private string GetFileNameFromUrl(string url)
{
if(string.IsNullOrEmpty(url))
return "image.jpg"; //or throw an ArgumentException
int sepIndex = url.LastIndexOf("/");
if(sepIndex == -1)
return "image.jpg"; //or throw an ArgumentException
return url.Substring(sepIndex);
}
Then you can use it like so:
string uri = "http://www.mywebsite.com/res/myimage.jpg";
WebClient client = new WebClient();
client.DownloadFile(uri, this.GetFileNameFromUrl(uri));
If you have no control over the url itself you might want to do some validation on it e.g. Regex.
Instead of parsing the url I suggest using function Path.GetFileName():
string uri = "http://yourserveraddress/fileName.txt";
string fileName = System.IO.Path.GetFileName(uri);
WebClient client = new WebClient();
client.DownloadFile(uri, fileName);
What about:
string url = "http://www.mywebsite.com/res/myimage.jpg?guid=2564";
Uri uri = new Uri(url);
string fileName = uri.Segments.Last();
Note: Last() is the extension method from Linq.

Howto: download a file keeping the original name in C#?

I have files on a server that can be accessed from a URL formatted like this:
http:// address/Attachments.aspx?id=GUID
I have access to the GUID and need to be able to download multiple files to the same folder.
if you take that URL and throw it in a browser, you will download the file and it will have the original file name.
I want to replicate that behavior in C#. I have tried using the WebClient class's DownloadFile method, but with that you have to specify a new file name. And even worse, DownloadFile will overwrite an existing file. I know I could generate a unique name for every file, but i'd really like the original.
Is it possible to download a file preserving the original file name?
Update:
Using the fantastic answer below to use the WebReqest class I came up with the following which works perfectly:
public override void OnAttachmentSaved(string filePath)
{
var webClient = new WebClient();
//get file name
var request = WebRequest.Create(filePath);
var response = request.GetResponse();
var contentDisposition = response.Headers["Content-Disposition"];
const string contentFileNamePortion = "filename=";
var fileNameStartIndex = contentDisposition.IndexOf(contentFileNamePortion, StringComparison.InvariantCulture) + contentFileNamePortion.Length;
var originalFileNameLength = contentDisposition.Length - fileNameStartIndex;
var originalFileName = contentDisposition.Substring(fileNameStartIndex, originalFileNameLength);
//download file
webClient.UseDefaultCredentials = true;
webClient.DownloadFile(filePath, String.Format(#"C:\inetpub\Attachments Test\{0}", originalFileName));
}
Just had to do a little string manipulation to get the actual filename. I'm so excited. Thanks everyone!
As hinted in comments, the filename will be available in Content-Disposition header. Not sure about how to get its value when using WebClient, but it's fairly simple with WebRequest:
WebRequest request = WebRequest.Create("http://address/Attachments.aspx?id=GUID");
WebResponse response = request.GetResponse();
string originalFileName = response.Headers["Content-Disposition"];
Stream streamWithFileBody = response.GetResponseStream();

retriving php variable in c#

I have a PHP script which redirects the user to a file download. Upon viewing this page in a web browser I am automatically prompted for a location to save the file, with the correct filename and extension inside the SaveFileDialog.
I wish to download this file using an application written in C#. How can I retrieve the filename and extension of the file that is included in the response from the PHP script?
I think have to read the PHP variable, but I have not found the correct method to read it.
The PHP variables in which I am storing the filename and extension are $file and $ext respectively.
I've read several questions here, but I'm confused. Some user speak about WebClient, others speak about HttpWebRequest.
Can you point me in the correct direction?
Take a look here, where the process of downloading and saving file is described.
Here's how to get file name from the request response headers:
String header = client.ResponseHeaders["content-disposition"];
String filename = new ContentDisposition(header).FileName;
And one more notice: here client is WebClient component. And here is how to use download with WebClient: enter link description here
------The full solution ----------------------------
As it turned out, your server uses authentication. That's why in order to download file we have to pass authentication. So, PLEASE write full details. And here's the code:
private class CWebClient : WebClient
{
public CWebClient()
: this(new CookieContainer())
{ }
public CWebClient(CookieContainer c)
{
this.CookieContainer = c;
}
public CookieContainer CookieContainer { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = this.CookieContainer;
}
return request;
}
}
static void Main(string[] args)
{
var client = new CWebClient();
client.BaseAddress = #"http://forum.tractor-italia.net/";
var loginData = new NameValueCollection();
loginData.Add("username", "demodemo");
loginData.Add("password", "demodemo");
loginData.Add("login","Login");
loginData.Add("redirect", "download/myfile.php?id=1622");
client.UploadValues("ucp.php?mode=login", null, loginData);
string remoteUri = "http://forum.tractor-italia.net/download/myfile.php?id=1622";
client.OpenRead(remoteUri);
string fileName = String.Empty;
string contentDisposition = client.ResponseHeaders["content-disposition"];
if (!string.IsNullOrEmpty(contentDisposition))
{
string lookFor = #"=";
int index = contentDisposition.IndexOf(lookFor, 0);
if (index >= 0)
fileName = contentDisposition.Substring(index + lookFor.Length+7);
}//attachment; filename*=UTF-8''JohnDeere6800.zip
client.DownloadFile(remoteUri, fileName);
}
On my PC that works.

Categories

Resources