简体   繁体   中英

Creating a file (.htm) in C#

I would like to know the best way to create a simple html file using c#.

Is it using something like System.IO.File.Create ?

Something like -

using (FileStream fs = new FileStream("test.htm", FileMode.Create)) 
{ 
    using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) 
    { 
        w.WriteLine("<H1>Hello</H1>"); 
    } 
} 

I'll say that File.WriteAllText is a stupid-proof way to write a text file for C# >= 3.5.

File.WriteAllText("myfile.htm", @"<html><body>Hello World</body></html>");

I'll even say that File.WriteAllLines is stupid-proof enough to write bigger html without fighting too much with string composition. But the "good" version is only for C# 4.0 (a little worse version is C# >= 2.0)

List<string> lines = new List<string>();
lines.Add("<html>");
lines.Add("<body>");
lines.Add("Hello World");
lines.Add("</body>");
lines.Add("</html>");

File.WriteAllLines("myfile.htm", lines);
// With C# 3.5
File.WriteAllLines("myfile.htm", lines.ToArray());

I would go with File.Create and then open a StreamWriter to that file if you dont have all the data when you create the file. This is a example from MS that may help you

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";

        // Create the file.
        using (FileStream fs = File.Create(path, 1024)) 
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

        // Open the stream and read it back.
        using (StreamReader sr = File.OpenText(path)) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}

Have a look at the HtmlTextWriter class. For an example how to use this class, for example look at http://www.dotnetperls.com/htmltextwriter .

Reading and writing text files and MSDN info . HTML is just a simple text file with *.HTML extension ;)

只需打开一个文件进行写入(例如使用File.OpenWrite ())将创建该文件(如果该文件尚不存在)。

If you have a look at http://msdn.microsoft.com/en-us/library/d62kzs03.aspx you can find an example of creating a file.

But how do you want to create the html file content? If that's just static then you can just write it to a file.. if you have to create the html on the fly you could use an ASPX file with the correct markup and use a Server.Execute to get the HTML as a string.

Yep, System.IO.File.Create(Path) will create your file just fine. You can also use a filestream and write to it. Seems more handy to write a htm file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM