How to Save Web page as html file using C# in UWP? - c#

I was working on a uwp project which uses webview to display webpages. I want to save a webpage locally from a url. I tried few these how to save the webpage using c#?
But it doesn't seem to be working as the solution is for a basic windows form app.
Please, forgive if I made any mistake asking question as I'm totally new to stackoverflow.

I want to save a webpage locally from a url.
It is similar to windows form. Try to send get request to the URL, and get the buffer or HTML content. For sending get request, you could use HttpClient. And then save the html buffer to a local file which format is .html. For example:
HttpClient httpclient = new HttpClient();
var result = await httpclient.GetBufferAsync(new Uri("https://www.microsoft.com/en-sg/"));
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("test2.html", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBufferAsync(file, result);
After downloaded you may find the downloaded file in C:\Users\{username}\AppData\Local\Packages\{PackageId}\LocalState.
For more details about file operations please reference Files, folders, and libraries.

Related

How can I download file in xamarin with webview?

I'm new in a Xamarin development. I hope that you can resolve my problem in a simple mode.
I've a crossplatform app developed with Xamarin and I want to download a file from a url.
I tried to download file using C# code but i can't do it (for crossplatform app) so I want to try other way. I want to use a webview and download the file directly into the web view. the problem is that when i click the button "download" into the webview it do anything. can you help me in a simply way?
my webview is this:
<WebView Source="https://download.cnet.com/Free-YouTube-Downloader/3001-2071_4-75219434.html/" x:Name="webv" WidthRequest="1000" HeightRequest="1000" />
it is an example of url
You have some plenty choices. But here's 2 of them. It's a simple one.
Using Device.OpenUri(new Uri("Download link here")).
This method is simple. It open the URL in client mobile web browser. And from there, the web browser will handle the background worker for download progress.
Using WebClient() class. Using this class, you'll can have your response in data type that you like maybe string or byte[]. Below's the sample:
var wb = new WebClient();
//Download as string
string x = wb.DownloadString("Download url");
//Download as byte[]
byte[] x = wb.DownloadData("Download Url");
From the return value of x, now you can rewrite it using System.IO to another file.
Note: These method is just basic. You can implement it in task, so your app will not hanging up while the download is in process.
Better approach: Via dependency service, download file from the native Android & iOS itself via interface class. you can check this one out: https://github.com/SimonSimCity/Xamarin-CrossDownloadManager#where-are-the-files-stored

Accessing downloaded file instead of page HTML

I have some code that connects to an HTTP API, and is supposed to get an XML response. When the API link is placed in a browser, the browser downloads the XML as a file. However, when the code connects to the same API, HTML is returned. I've told the API owner but they don't think anything is wrong. Is there a way to capture the downloaded file instead of the HTML?
I've tried setting the headers to make my code look like a browser. Also tried using WebRequest instead of WebClient. But nothing works.
Here is the code, the URL works in the browser (file downloaded) but doesn't work for WebClient:
WebClient webClient = new WebClient();
string result = webClient.DownloadString(url);
The code should somehow get the XML file instead of the page HTML (actually the HTML doesn't appear in the browser, only the file).
The uri that you access may be a HTML page that have its own mechanism (like generating the actual download address which may be dynamically generated by the server and redirecting to it, in order to prevent external linking access) to access the real file.
It is supposed to use a browser background browser core like CefSharp to run the HTML and its javascript to let it navigate, and probably you may want to hook the download event to handle the downloading.
I think you need to add accept header to the WebClient object.
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.Accept] = "application/xml;q=1";
string result = webClient.DownloadString(url);
}
Thank you all for your input. In the end, it was caused by our vendor switching to TLS 1.2. I just had to force my code to use 1.2 and then it worked.

C# windows service: HTML page with picture, CSS and JS as a response

I am learning to build a windows service, but it takes requests (e.g. localhost:8081/index) from the browser to. Therefore, the HTTP response should contain an HTML page.
The HTML page looks okay when I double click the index.html file, but it lost all the CSS and js files when I request from the web browser. And I open the developer's tool in chrome and found out that all the CSS and JS files were corrupted and contain the code from my HTML page (weird).
I used HttpListenerContext class to listen for http://localhost/index request, and then open index.html file and used File.ReadAllBytes(file). When composing the response, I used the following code:
responseBytes = File.ReadAllBytes(file);
response.ContentLength64 = responseBytes.Length;
await response.OutputStream.WriteAsync(responseBytes, 0, responseBytes.Length);
response.OutputStream.Close();
Can anyone help me to figure out why this is happening?
So I figured out the answer by myself when I traced the code. When request localhost/index comes in from the browser, the GET method will first acquire index.html first, then there are other GET requests come in for the CSS, image and JS as well (It's weird that I didn't see the later requests before.)
Then I updated the handler to compose responses contains CSS, image and JS files. Everything works perfectly now.

Download from url that generates a file

I need to be able to download a file from url. The url does not link to an actual file instead it generates the file on the server first and then gives a download dialog. Probably returning an mvc FileResult.
I'm just interested in getting the byte[] from the file.
I've tried:
using (var webClient = new WebClient())
{
System.Uri uri = new System.Uri(Document.Url);
bytes = await webClient.DownloadDataTaskAsync(uri);
}
This works but I get a corrupted file as expected.
I do not have control over how the server generates or serves the file.
Any way to wait for the file to complete generating and then get the file content?
TIA
Never mind. Turns out the link returns some javascript that auto authenticates a user and then does a jquery get to another url and port to generate the file. So I was basically downloading that script and saving it to pdf. doh.
So a work around would be to mimic that in some way.

Use HTML string from Server Requets, and create the web page without saving it a file [in C#]

I´m sending the value of a variable via POST to a PHP page in C#. I get the data stream from the server that has all the web page in HTML with the value of the POST. This information is stored in a string variable.
I would like to open a browser and show the web page (maybe using System.Diagnostics.Process.Start("URL")), without having to save it in a file, this is showing the page in the moment and, when the browser is closed, no file is stored in the server.
Any idea?
Drop a WebBrowser control into a new form webBrowser1 and set its DocumentTextProperty to your result html
webBrowser1.DocumentText = ("<html><body>hello world</body></html>");
source:
<html><body>hello world</body></html>
You aren't going to be able to do that in an agnostic way.
If you simply wanted to open the URL in a browser, then using the Process class would work.
Unfortunately, in your case, you already have the content from creating the POST to the server, and you really want to stream that response in your application to the browser.
It's possible among the some browsers, but it's not able to be done in an agnostic way (and it's complicated even when targeting a specific browser).
To complicate matters, you want the browser to believe that the stream you are sending it is really coming from the server, when in reality, it's not.
I believe that your best bet would be to save the response to the file system in a temp file. However, before you do, add the <base> tag to the file with the URL that the file came from. This way, relative URLs will resolve correctly when rendered in the browser.
Then, just open the temporary file in the browser using the Process class.

Categories