我是C#的新手。如何将数据写入一个文件?到目前为止,这是我的代码:
public void convertHTML(string strData, string strTitle)
{
int position = strTitle.LastIndexOf('.');
strTitle = strTitle.Remove(position);
strTitle= strTitle + ".html";
StreamWriter sw = new StreamWriter(strTitle); //strTitle is FilePath
sw.WriteLine("<html>");
sw.WriteLine("<head><title>{0}</title></head>",strTitle);
//MessageBox.Show("this editor");
sw.WriteLine("<body>");
sw.WriteLine(strData); //strData is having set of lines
sw.WriteLine("</body>");
sw.WriteLine("</html>");//*/
lstHtmlFile.Items.Add(strTitle);
}
它只会创建一个空白的html文件,它没有任何数据
答案 0 :(得分:3)
您需要刷新并关闭StreamWriter
:
using (StreamWriter sw = new StreamWriter(strTitle))
{
sw.WriteLine("<html>");
sw.WriteLine("<head><title>{0}</title></head>",strTitle);
sw.WriteLine("<body>");
sw.WriteLine(strData);
sw.WriteLine("</body>");
sw.WriteLine("</html>");
}
使用using
可以解决问题。
答案 1 :(得分:1)
您可以使用添加块来清理non managed object
using (var streamWriter = new StreamWriter(strTitle))
{
....
}
链接:http://msdn.microsoft.com/fr-fr/library/vstudio/yh598w02.aspx