Automatically download an xml file from URI with download popup - c#

ASP.NET MVC 4 Razor:
I've been working at this for a bit, so I apologize if I'm missing something obvious, but I will truly appreciate any assistance that could be offered.
In a nutshell, what I'm looking to do is download an XML file from a URI using C#. It ought to be pretty straightforward, but the URI leads to a blank page with a download prompt popup populated with a dynamically created filename.
I can't provide the URI due to its confidential nature, but here is the code I've been toying with. (Forgive my ignorance on this matter, it's the first time I've tried anything like this)
byte[] data;
using (WebClient Client = new WebClient())
{
data = Client.DownloadData(uriString + fileString);
}
File.WriteAllBytes(dirString + fileString, data);
I've also tried:
using (WebClient Client = new WebClient())
{
Client.DownloadFile(uriString + fileString, dirString + fileString);
}
To be honest, this code doesn't really work for me. The downloaded files aren't correct. The XML files appear to contain the code from the webpage they've been downloaded from, and if I try something like an image, the image is broken. So, again, any assistance would be appreciated.
Thanks in advance!

The URI that you are using is probably wrong. You are using the URI that opens the popup page. The popup page should be doing another GET to the dynamically generated file.
To automate this process, you should use a WebRequest to get the contents of the popup page. Scrape the contents of the page to get the actual URL to download the file. Then use the code you have written to download the file.
var request = WebRequest.Create("PopupUrl");
var response = request.GetResponse();
string url = GetUrlFromResponseByRegExOrXMLParsing();
var client = new WebClient();
webClient.DownloadFile(url, filePath);

Related

File download does not start when invoke or execute an URL

If anyone load this url https://de.visiblealpha.com/links/80488d55-ae41-4def-9452-bae3ac2e2b06 into browser then a excel file start download. so when i invoke the same url by HttpWebRequest then excel file does not start download. this code example i tried.
string address = "https://de.visiblealpha.com/links/80488d55-ae41-4def-9452-bae3ac2e2b06";
using (WebClient client = new WebClient())
{
client.DownloadString(address);
}
again i tried this one too.
string url = "https://de.visiblealpha.com/links/80488d55-ae41-4def-9452-bae3ac2e2b06";
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
but failed to reach my goal. code successfully executed but no excel file start downloading which i am trying to achieve.
when i tried to load this url https://de.visiblealpha.com/links/80488d55-ae41-4def-9452-bae3ac2e2b06 into webbrowser control then also saw same problem no excel file start download. here is code which i tried.
webBrowser1.Navigate("https://de.visiblealpha.com/links/80488d55-ae41-4def-9452-bae3ac2e2b06");
webBrowser1.ScriptErrorsSuppressed = true;
i just do not understand why excel file is not getting download when invoke or execute the same very url.
so please some one tell me what i need to do as a result the moment i will execute the url excel file will start downloading in client pc.
please share some working code example.
DownloadString returns the contents into a variable aka in memory. A file will not get saved on the system. If that is what you intended, there's a small change you need to make in your code:
string address = "https://de.visiblealpha.com/links/80488d55-ae41-4def-9452-bae3ac2e2b06";
using (WebClient client = new WebClient())
{
string contents = client.DownloadString(address);
}
The variable "contents" will contain html of the URL in your question. If you want it as a file, then I you need to use DownloadFile method instead. The spreadsheet itself is a different URL.
There's an example at the end of this documentation.

How to detect the origin of a webpage's GET requests programmatically? (C#)

In short, I need to detect a webpage's GET requests programmatically.
The long story is that my company is currently trying to write a small installer for a piece of proprietary software that installs another piece of software.
To get this other piece of software, I realize it's as simple as calling the download link through C#'s lovely WebClient class (Dir is just the Temp directory in AppData/Local):
using (WebClient client = new WebClient())
{
client.DownloadFile("[download link]", Dir.FullName + "\\setup.exe");
}
However, the page which the installer comes from does is not a direct download page. The actual download link is subject to change (our company's specific installer might be hosted on a different download server another time around).
To get around this, I realized that I can just monitor the GET requests the page makes and dynamically grab the URL from there.
So, I know I'm going to do, but I was just wondering, is there was a built-in part of the language that allows you to see what requests a page has made? Or do I have to write this functionality myself, and what would be a good starting point?
I think I'd do it like this. First download the HTML contents of the download page (the page that contains the link to download the file). Then scrape the HTML to find the download link URL. And finally, download the file from the scraped address.
using (WebClient client = new WebClient())
{
// Get the website HTML.
string html = client.DownloadString("http://[website that contains the download link]");
// Scrape the HTML to find the download URL (see below).
// Download the desired file.
client.DownloadFile(downloadLink, Dir.FullName + "\\setup.exe");
}
For scraping the download URL from the website I'd recommend using the HTML Agility Pack. See here for getting started with it.
I think you have to write your own "mediahandler", which returns a HttpResponseMessage.
e.g. with webapi2
[HttpGet]
[AllowAnonymous]
[Route("route")]
public HttpResponseMessage GetFile([FromUri] string path)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(path, FileMode.Open, FileAccess.Read));
string fileName = Path.GetFileNameWithoutExtension(path);
string disposition = "attachment";
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(disposition) { FileName = fileName + Path.GetExtension(absolutePath) };
result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(Path.GetExtension(path)));
return result;
}

Download .aspx file from WebClient object

I'm trying to download a ".aspx" file from the web server using a WebClient object and save it to the file system, but it raises an exception of "HTTP 500 Internal Error", I think becuase the server tries to render the html and send the content of the same rather than the file itself.
var objWebClient = new WebClient();
var remoteUrl = "someserverURL" + "default.aspx";
objWebClient.DownloadFile(remoteUrl, localPathToSave);
Tried adding HTTP headers but I think they might not be of use with request object being from a desktop system and not a browser, have set the server, to serve all content in "application/octet-stream" format.
You can't do this.
If the web server is set up correctly, it will not allow you to directly download an aspx file.
The reason it downloads all your other files like jpegs and text files is because the web server will happily serve these file types and allow them to be downloaded.
If what you are attempting to do was possible then anyone would be able to download the aspx source files for any .net site, which would be hugely insecure.
What you could do is to get the rendered html content from the .aspx page and save that.
var webClient = new WebClient();
var remoteUrl = "someserverURL" + "default.aspx";
byte[] data = webClient.DownloadData(remoteUrl);
var utf8Encoding = new UTF8Encoding();
var html = utf8Encoding.GetString(data);
//now you could save the html to a file

Moving XML file to be hosted

Please be gentle. I am not a terribly proficient developer!
So this is the last thing I need to fix in my Windows Phone 7.5 app before I consider it done. In short, the data sources on the menus are driven by an xml file. That file is stored locally with the app. I would like to store that file somewhere on the Internet). Currently if I need to make a change to this xml file, I have to re-submit the app to the Marketplace taking about 5 days before the change goes live. How 2003 of me.
So I can't figure out what they are expecting returned in the code below. I've hacked away and it always give some error I don't understand.
I've set the filename variable to a URL of a file on the Internet but apparently that is not supported. So I either need a new way for that whole section to work or a way to convert the hosted filename converted into something that will work.
private static void FirstLaunch()
{
// On the first launch, just add everything from the OPML file
string filename;
//This file should really be hosted on the Internet somewhere.
filename = "/RSSReader;component/LyncNews-opml.xml";
StreamResourceInfo xml = App.GetResourceStream(new Uri(filename, UriKind.Relative));
List<RSSPage> rssPages = ParseOPML(xml.Stream);
}
You can set it to a URL, but you'll need to download the content, not through App.GetResourceStream. Try WebClient, it's easy and simple.
A simple usage:
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Client_DownloadStringCompleted);
Uri token = new Uri("your url");
client.DownloadStringAsync(token);
and handle xml parsing in the event.

How to download an image using a URL with a query string instead of image path?

I'm doing a C# windows application, and need to know how to download a picture which has a link with a query string, for example www.mywebsite.com/img.aspx?imgid=12345 (which automatically redirects to the appropriate image based on imgid). I need to then save the file to the disk somewhere. I don't need any big fancy download manager, just the cleanest way to get such an image from a redirecting URL.
You should be able to do it like this:
using (WebClient Client = new WebClient ())
{
Client.DownloadFile("http://www.mywebsite.com/img.aspx?imgid=12345", "12345.jpg");
}
Use the WebClient class and he DownloadFile method.
http://msdn.microsoft.com/en-us/library/ez801hhe.aspx
It's perfectly acceptable to pass a querystring parameter in the URI of the method.
Your file will be at bin/debug folder, and give the extension in which your browser download the file. like
{
using (WebClient client = new WebClient()) {
client.DownloadFile("http://www.mywebsite.com/img.aspx?imgid=12345", "selectedfile.gif");
}
}

Categories

Resources