将 c# 字符串保存为 html 文件

save a c# string as a html file

我有一个 C# 脚本,它有时会创建一个字符串变量,我如何才能将它保存为脚本同一目录中的 HTML 文件?

 string saveHtml = "<html>" +
    "<head>" +
    "  <title>Select Image</title>" +
    "  <script type=\"text/javascript\">" +
    "  function displayImage(elem) {" +
    "    var image = document.getElementById(\"canvas\");" +
    "    image.src = elem.value;        " +
    "  }" +
    "  </script>" +
    "</head>" +
    "<body>" +
    "  <form name=\"controls\">" +
    "    <img id=\"canvas\" src=\"pictures/fire1.jpg\" />" +
    "    <select name=\"imageList\" onchange=\"displayImage(this);\">" +
    "      <option value=\"pictures/001JRPchargeable.png\">Fire 1</option>" +
    "      <option value=\"pictures/001JRPNonchargeable.png\">Fire 2</option>" +
"</select>" +
"  </form>" +
"</body>" +
"</html>";

您可以使用此代码:

string saveHtml = "<html>" +
    "<head>" +
    "  <title>Select Image</title>" +
    "  <script type=\"text/javascript\">" +
    "  function displayImage(elem) {" +
    "    var image = document.getElementById(\"canvas\");" +
    "    image.src = elem.value;        " +
    "  }" +
    "  </script>" +
    "</head>" +
    "<body>" +
    "  <form name=\"controls\">" +
    "    <img id=\"canvas\" src=\"pictures/fire1.jpg\" />" +
    "    <select name=\"imageList\" onchange=\"displayImage(this);\">" +
    "      <option value=\"pictures/001JRPchargeable.png\">Fire 1</option>" +
    "      <option value=\"pictures/001JRPNonchargeable.png\">Fire 2</option>" +
"</select>" +
"  </form>" +
"</body>" +
"</html>";


string path = @"D:\Test.html";
System.IO.File.WriteAllText(path, saveHtml)

Michael Randall所述:

class Program
{
    static void Main(string[] args)
    {
        string saveHtml = "<html>" +
                          "<head>" +
                          "  <title>Select Image</title>" +
                          "  <script type=\"text/javascript\">" +
                          "  function displayImage(elem) {" +
                          "    var image = document.getElementById(\"canvas\");" +
                          "    image.src = elem.value;        " +
                          "  }" +
                          "  </script>" +
                          "</head>" +
                          "<body>" +
                          "  <form name=\"controls\">" +
                          "    <img id=\"canvas\" src=\"pictures/fire1.jpg\" />" +
                          "    <select name=\"imageList\" onchange=\"displayImage(this);\">" +
                          "      <option value=\"pictures/001JRPchargeable.png\">Fire 1</option>" +
                          "      <option value=\"pictures/001JRPNonchargeable.png\">Fire 2</option>" +
                          "</select>" +
                          "  </form>" +
                          "</body>" +
                          "</html>";

        File.WriteAllText(@"C:\temp\theFile.html", saveHtml);
    }
}