3

I want to make it so that by pressing a button on the homepage a user will be able to create a new html page on the server of the website (e.g. www.example.com/0002.html) I need this page to be always there and accessible by everyone. How can one create a html page programmably using asp.net?

JoeWinrow
  • 31
  • 1
  • 1
  • 2

5 Answers5

6

To create a file on the server, your server side code would need to use a FileStream to write to the disk, just like you would write to the disk in a normal desktop application. The one thing you would need to do is write it inside of the directory which holds your site.

Some code to write a file:

using (StreamWriter sw = new StreamWriter(Server.MapPath("fileName.html")))
    using (HtmlTextWriter writer = new HtmlTextWriter(sw))
    {
        writer.RenderBeginTag(HtmlTextWriterTag.Html);

        writer.RenderBeginTag(HtmlTextWriterTag.Head);
        writer.Write("Head Contents");
        writer.RenderEndTag();

        writer.RenderBeginTag(HtmlTextWriterTag.Body);
        writer.Write("Body Contents");
        writer.RenderEndTag();

        writer.RenderEndTag();
    }
Dan McClain
  • 11,780
  • 9
  • 47
  • 67
  • Thank you! This was my first time asking a question here. You guys are awesome. – JoeWinrow Mar 30 '11 at 10:59
  • Hi thank you for your answer. I want to have 0001.html created the first time and then next button to create 0002.html and so on. What is the best way to keep track of the latest page number created to always create unique pages? Where can I store the value? – JoeWinrow Mar 30 '11 at 11:18
1
protected void Button1_Click(object sender, EventArgs e)
{
    string body = "<html><body>Web page</body></html>";

    //number of current file
    int filenumber = 1;
    string numberFilePath = "/number.txt";
    //change number if some html was already saved and number.txt was created
    if (File.Exists(Server.MapPath(numberFilePath)))
    {
        //open file with saved number
        using (StreamReader sr = new StreamReader(numberFilePath))
        {
            filenumber = int.Parse(sr.ReadLine()) + 1;
        }
    }
    using (StreamWriter sw = new StreamWriter(Server.MapPath(filenumber.ToString("D4") + ".html")))
    {
        sw.Write(body);
        //write last saved html number to file
        using (StreamWriter numberWriter = new StreamWriter(Server.MapPath(numberFilePath), false))
        {
            numberWriter.Write(filenumber);
        }
    }
}

This is simpliest way I can think of. I didn't test it but it should work. Anyway it's better to use database for that kind of things. And I didn't add any try-catch code to keep code simple...

Episodex
  • 4,479
  • 3
  • 41
  • 58
  • You should wrap your StreamWriter in a Using statement, to ensure that it is properly disposed of. – Dan McClain Mar 30 '11 at 10:53
  • Hi thank you for your answer. I want to have 0001.html created the first time and then next button to create 0002.html and so on. What is the best way to keep track of the latest page number created to always create unique pages? Where can I store the value? – JoeWinrow Mar 30 '11 at 11:18
  • You can store the value in database or in a file. I'll add file example in my code. – Episodex Mar 30 '11 at 12:25
  • No need for any Stream at all, the `File` class provides static methods to create and write to text files in one line. No need to store the last value, you can iterate the existing file to find the "maximum" value. – Shadow The GPT Wizard Mar 30 '11 at 12:55
0

Just create a new file and save it somewhere that is publicly accessible with the .html file extension. Here's a short script from another SO question:

using (StreamWriter w = new StreamWriter(Server.MapPath("~/page.html"), true))
{
    w.WriteLine("<html><body>Hello dere!</body></html>"); // Write the text
}
Community
  • 1
  • 1
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
  • Hi thank you for your answer. I want to have 0001.html created the first time and then next button to create 0002.html and so on. What is the best way to keep track of the latest page number created to always create unique pages? Where can I store the value? – JoeWinrow Mar 30 '11 at 11:18
0

At it's most basic you could just use a stream writer to make a new text file with the HTML markup inside of it.

var filePath = ""; // What ever you want your path to be

var contentOfPage = "<html>Whatever you are writing</html>";

using (StreamWriter writer = new StreamWriter(Server.MapPath(filePath))
{
   writer.WriteLine(contentOfPage);
}

Importantly how are you going to decide what the filenames will be? If you don't add in a mechanism for this you'll just be overwriting the same file every time!

Now you can use the inbuilt .Net method, it's pretty ugly but it works I suppose.

fileName = System.IO.Path.GetRandomFileName();

// You may want to put an html on the end in your case
fileName = System.IO.Path.GetRandomFileName() + ".html";

Here I'd probably implement a bespoke way if I made it, for SEO purposes, but if that's not important

SamMullins
  • 267
  • 4
  • 9
0

Based on your comments, what you need is such code in the button click event code:

//get all HTML files in current directory that has numeric name:
string strRootPath = Server.MapPath(".");
List<string> arrExistingFiles = Directory.GetFiles(strRootPath, "*.html").ToList().FindAll(fName =>
{
    int dummy;
    return Int32.TryParse(Path.GetFileNameWithoutExtension(fName), out dummy);
});

//calculate next number based on the maximum file name, plus 1:
int nextFileNumber = arrExistingFiles.ConvertAll(fName => Int32.Parse(Path.GetFileNameWithoutExtension(fName))).Max() + 1;

//generate file name with leading zeros and .html extension:
string strNewFileName = nextFileNumber.ToString().PadLeft(5, '0') + ".html";
string strNewFilePath = Server.MapPath(strNewFileName);

//write contents:
File.WriteAllText(strNewFilePath, body);

//let user option to see the file:
litCreateFileResult.Text = string.Format("File created successfully. <a href=\"{0}\" target=\"_blank\">View</a>", strNewFileName);

The code is pretty much commented, the only thing worth adding is the last line, for this to work add this to your .aspx form:

<asp:Literal ID="litCreateFileResult" runat="server" />
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208