为什么我调用 file.WriteLine() 无法将 StringBuilder 的所有内容写入文件?

Why does my call to file.WriteLine() fail to write all contents of the StringBuilder to the file?

我正在尝试通过 StringBuilder 和 File.WriteLn() 将一个 html 文件写入磁盘,但是该文件缺少几行,因此没有用。我的代码是:

    private void BuildAndWriteHTMLFile()
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<!DOCTYPE html>");
    sb.Append("<html lang=\"en\">");
    sb.Append("<head>");
    sb.Append("<meta charset=\"utf-8\">");
    sb.Append("<title>Green Bay Packers 2013 Schedule (All times Central)</title>");
    sb.Append("<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js\"></script> ");
    sb.Append("<script src=\"http://maps.google.com/maps/api/js?sensor=false\"></script> ");
    sb.Append("<script src=\"gomap.js\"></script> ");
    sb.Append("<!--[if IE]>");
    sb.Append("<script src=\"http://html5shiv.googlecode.com/svn/trunk/html5.js\"></script>");
    sb.Append("<![endif]-->");

. . . // oodles on noodly code elided for lack of reason to leave it in

    sb.Append("this.singleMarker = false;");
    sb.Append("this.lockGeocode = false;");
    sb.Append("this.markers = [];");
    sb.Append("this.tmpMarkers = [];");
    sb.Append("this.geoMarkers = [];");
    sb.Append("},");

    sb.Append("isVisible: function(latlng) {");
    sb.Append("return this.map.getBounds().contains(latlng);");
    sb.Append("}");
    sb.Append("}");
    sb.Append("})(jQuery);");

    sb.Append("$(function() {");

    sb.Append("$(\"#map\").goMap({ ");
    sb.Append("latitude: 36.75,  ");
    sb.Append("longitude: -100, ");
    sb.Append("maptype: 'ROADMAP',");
    sb.Append("zoom: 5");
    sb.Append("}); ");

    sb.Append("$.goMap.createMarker({");
    sb.Append("address: 'Green Bay, Wisconsin',");
    sb.Append("title: 'Lambeau Field, Green Bay, WI',");
    sb.Append("html: '<h1>Green Bay Packers Home Games</h1><p class=\"away\">Game 1, Week 1) Sunday Sept. 8 at SAN FRANCISCO 49ERS  3:25 p.m.</p><p>Game 2, Week 2) Sunday Sept. 15 WASHINGTON REDSKINS Noon</p><p class=\"away\">Game 3, Week 3) Sunday Sept. 22 at CINCINNATI BENGALS Noon</p><p>Game 4, Week 5) Sunday Oct. 6    DETROIT LIONS       Noon</p><p class=\"away\">Game 5, Week 6) Sunday Oct. 13 at BALTIMORE RAVENS        Noon</p><p>Game 6, Week 7) Sunday Oct. 20   CLEVELAND BROWNS    3:25 p.m.</p><p class=\"away\">Game 7, Week 8) Sunday Oct. 27 at MINNESOTA VIKINGS  7:30 p.m.</p><p>Game 8, Week 9) Monday Nov. 4   CHICAGO BEARS       7:40 p.m.</p><p>Game 9, Week 10) Sunday Nov. 10 PHILADELPHIA EAGLES     Noon</p><p class=\"away\">Game 10, Week 11) Sunday Nov. 17 at NEW YORK GIANTS   7:30 p.m. (flex)</p><p>Game 11, Week 12) Sunday Nov. 24 MINNESOTA VIKINGS   Noon (flex)</p><p class=\"away\">Game 12, Week 13) Thursday Nov. 28 at DETROIT LIONS    11:30 a.m.  </p><p>Game 13, Week 14) Sunday Dec. 8  ATLANTA FALCONS     7:30 p.m. (flex)</p><p class=\"away\">Game 14, Week 15) Sunday Dec. 15 at DALLAS COWBOYS    3:25 p.m. (flex)</p><p>Game 15, Week 16) Sunday Dec. 22 PITTSBURGH STEELERS 3:25 p.m. (flex)</p><p class=\"away\">Game 16, Week 17) Sunday Dec. 29 at CHICAGO BEARS Noon (flex)</p><p class=\"away\">SUPER BOWL Sunday Feb. 2, 2014 vs ?</p>'");
    //sb.Append("html: '<h1>Green Bay Packers Home Games</h1><p class=\"away\">Game 1, Week 1) Sunday Sept. 8 at SAN FRANCISCO 49ERS    3:25 p.m.</p><p>Game 2, Week 2) Sunday Sept. 15 WASHINGTON REDSKINS Noon</p><p class=\"away\">Game 3, Week 3) Sunday Sept. 22 at CINCINNATI BENGALS Noon</p><p>Game 4, Week 5) Sunday Oct. 6    DETROIT LIONS       Noon</p><p class=\"away\">Game 5, Week 6) Sunday Oct. 13 at BALTIMORE RAVENS        Noon</p><p>Game 6, Week 7) Sunday Oct. 20   CLEVELAND BROWNS    3:25 p.m.</p><p class=\"away\">Game 7, Week 8) Sunday Oct. 27 at MINNESOTA VIKINGS  7:30 p.m.</p><p>Game 8, Week 9)");
    //sb.Append("Monday Nov. 4  CHICAGO BEARS       7:40 p.m.</p><p>Game 9, Week 10) Sunday Nov. 10 PHILADELPHIA EAGLES     Noon</p><p class=\"away\">Game 10, Week 11) Sunday Nov. 17 at NEW YORK GIANTS   7:30 p.m. (flex)</p><p>Game 11, Week 12) Sunday Nov. 24 MINNESOTA VIKINGS   Noon (flex)</p><p class=\"away\">Game 12, Week 13) Thursday Nov. 28 at DETROIT LIONS    11:30 a.m.  </p><p>Game 13, Week 14) Sunday Dec. 8  ATLANTA FALCONS     7:30 p.m. (flex)</p><p class=\"away\">Game 14, Week 15) Sunday Dec. 15 at DALLAS COWBOYS    3:25 p.m. (flex)</p><p>Game 15, Week 16)");
    //sb.Append("Sunday Dec. 22 PITTSBURGH STEELERS 3:25 p.m. (flex)</p><p class=\"away\">Game 16, Week 17) Sunday Dec. 29 at CHICAGO BEARS Noon (flex)</p><p class=\"away\">SUPER BOWL Sunday Feb. 2, 2014 vs ?</p>'");
    sb.Append("});");

    sb.Append("});");
    sb.Append("</script>");
    sb.Append("</body>");
    sb.Append("</html>");

    string nameOfFile = string.Format(@"C:\misc\mapcode_{0}", GetFileNameDateTimeExtension());
    if (!File.Exists(nameOfFile))
    {
        StreamWriter file = new StreamWriter(@nameOfFile);
        file.WriteLine(sb.ToString());
        urlOfGeneratedFile = string.Format("file:///{0}", nameOfFile);
        webBrowser1.Url = new Uri(urlOfGeneratedFile);
    }
}

问题是写入的文件是 StringBuilder 中内容的截断版本。它首先截断了附加的最后几行(写入的文件以“NEW YORK G”结尾);当我在结束脚本、正文和 html 标记之前注释掉最后一个 createMarker 部分时,文件结束于“this.lockGeocode = false;this.markers = [];this.tmpMarkers = [];this.geoM"

就好像在所有行都写入 StringBuilder 之前就完成了文件写入。

我需要调用 Flush、Sleep 方法还是什么?

如果您为 StreamWriter 使用 using 块,这应该会按预期工作。

using(StreamWriter file = new StreamWriter(@nameOfFile)) 
  file.WriteLine(sb.ToString());
urlOfGeneratedFile = string.Format("file:///{0}", nameOfFile);
webBrowser1.Url = new Uri(urlOfGeneratedFile);

否则,是的,使用 StreamWriter.Flush 或将 StreamWriter.AutoFlush 设置为 true。

您不是 StreamWriter 的 closing/disposing,编写器有一个内部缓冲区,在您关闭流之前不会写出。将编写器包装在 using 语句中以在完成后自动关闭文件。

if (!File.Exists(nameOfFile))
{
    using(StreamWriter file = new StreamWriter(@nameOfFile))
    {
        file.WriteLine(sb.ToString());
    }
    urlOfGeneratedFile = string.Format("file:///{0}", nameOfFile);
    webBrowser1.Url = new Uri(urlOfGeneratedFile);

}

但是,您的代码可以简化为不使用 StreamWriter 而只是调用 File.WriteAllText

if (!File.Exists(nameOfFile))
{
    File.WriteAllText(@nameOfFile,sb.ToString());
    urlOfGeneratedFile = string.Format("file:///{0}", nameOfFile);
    webBrowser1.Url = new Uri(urlOfGeneratedFile);

}

UPDATE:其实和File.WriteAllText会有细微的差别,file.WriteLine会在文末多加一个换行符, File.WriteAllText不会。如果换行符对您很重要,请在调用 File.WriteAllText.

之前添加 sp.AppendLine();