Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save string content to a local file

Tags:

c#

c#-3.0

c#-4.0

I am developing an application which is showing web pages through a web browser control.

When I click the save button, the web page with images should be stored in local storage. It should be save in .html format.

I have the following code:

WebRequest request = WebRequest.Create(txtURL.Text);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;

using (StreamReader sr = new StreamReader(data))
{
    html = sr.ReadToEnd();
}

Now string html contains the webpage content. I need to save this into D:\Cache\

How do i save the html contents to disk?

like image 302
Deena Avatar asked Sep 03 '25 05:09

Deena


1 Answers

You can use this code to write your HTML string to a file:

var path= @"D:\Cache\myfile.html";
File.WriteAllText(path, html);

Further refinement: Extract the filename from your (textual) URL.

Update: See Get file name from URI string in C# for details. The idea is:

var uri = new Uri(txtUrl.Text);

var filename = uri.IsFile 
  ? System.IO.Path.GetFileName(uri.LocalPath)
  : "unknown-file.html";
like image 177
JimiLoe Avatar answered Sep 04 '25 19:09

JimiLoe