0

我是 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 文件

4

2 回答 2

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就可以了。

于 2012-09-20T08:16:46.870 回答
1

您可以添加块使用以清洁您的non managed object

using (var streamWriter = new StreamWriter(strTitle))
{

 ....
}

链接:http: //msdn.microsoft.com/fr-fr/library/vstudio/yh598w02.aspx

于 2012-09-20T08:38:51.213 回答