在C#中创建文件(.htm)

我想知道使用c#创建一个简单的html文件的最佳方法。

它是否使用类似System.IO.File.Create东西?

就像是 –

 using (FileStream fs = new FileStream("test.htm", FileMode.Create)) { using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) { w.WriteLine("

Hello

"); } }

我会说File.WriteAllText是一种为C#> = 3.5编写文本文件的愚蠢方法。

 File.WriteAllText("myfile.htm", @"Hello World"); 

我甚至会说File.WriteAllLines是足够愚蠢的,可以编写更大的html,而不会对字符串组成进行过多的打击。 但“好”版本仅适用于C#4.0(更糟糕的版本是C#> = 2.0)

 List lines = new List(); lines.Add(""); lines.Add(""); lines.Add("Hello World"); lines.Add(""); lines.Add(""); File.WriteAllLines("myfile.htm", lines); // With C# 3.5 File.WriteAllLines("myfile.htm", lines.ToArray()); 

如果您在创建文件时没有所有数据,我会使用File.Create然后打开StreamWriter到该文件。 这是MS可以帮助您的一个例子

 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); } } } } 

看看HtmlTextWriter类。 有关如何使用此类的示例,请访问http://www.dotnetperls.com/htmltextwriter 。

读取和写入文本文件和MSDN信息 。 HTML只是一个带* .HTML扩展名的简单文本文件;)

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

如果您查看http://msdn.microsoft.com/en-us/library/d62kzs03.aspx ,可以找到创建文件的示例。

但是你想如何创建html文件内容呢? 如果那只是静态的那么你可以把它写到文件中……如果你必须动态创建html,你可以使用带有正确标记的ASPX文件,并使用Server.Execute将HTML作为字符串。

是的, System.IO.File.Create(Path)会很好地创建你的文件。 您还可以使用文件filestream并写入它。 编写htm文件似乎更方便