44

如果我在磁盘上有一个 HTML 文件,如何在运行时一次将其全部读入 String 变量?然后我需要对该字符串变量进行一些处理。

一些像这样的html文件:

<html>
    <table cellspacing="0" cellpadding="0" rules="all" border="1" style="border-width:1px;border-style:solid;width:274px;border-collapse:collapse;">
        <COLGROUP><col width=35px><col width=60px><col width=60px><col width=60px><col width=59px></COLGROUP>
        <tr style="height:20px;">
            <th style="background-color:#A9C4E9;"></th><th align="center" valign="middle" style="color:buttontext;background-color:#D3DCE9;">A</th><th align="center" valign="middle" style="color:buttontext;background-color:#D3DCE9;">B</th><th align="center" valign="middle" style="color:buttontext;background-color:#D3DCE9;">C</th><th align="center" valign="middle" style="color:buttontext;background-color:#D3DCE9;">D</th>
        </tr><tr style="height:20px;">
            <th align="center" valign="middle" style="color:buttontext;background-color:#E4ECF7;">1</th><td align="left" valign="top" style="color:windowtext;background-color:window;">Hi</td><td align="left" valign="top" style="color:windowtext;background-color:window;">Cell Two</td><td align="left" valign="top" style="color:windowtext;background-color:window;">Actually a longer text</td><td align="left" valign="top" style="color:windowtext;background-color:window;">Final Word</td>
        </tr>
    </table>
</html>
4

8 回答 8

64

使用File.ReadAllText传递文件位置作为参数。

但是,如果您的真正目标是解析 html,那么我建议您使用Html Agility Pack

于 2012-08-29T18:07:01.483 回答
21

利用System.IO.File.ReadAllText(fileName)

于 2012-08-29T18:07:04.107 回答
17
string html = File.ReadAllText(path);
于 2012-08-29T18:07:29.067 回答
12

这大部分已经涵盖了,但是当我遇到以前的代码示例的问题时添加了一个。

Dim strHTML as String = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/folder/filename.html"))
于 2014-10-21T12:57:44.687 回答
5

用于File.ReadAllText(path_to_file)阅读

于 2012-08-29T18:10:34.413 回答
4

您要进行哪种处理?你可以XmlDocument doc = new XmlDocument();跟着做doc.Load(filename)。然后可以在内存中解析 XML 文档。

阅读此处了解有关 XmlDocument 的更多信息:

于 2012-08-29T18:09:56.383 回答
4

你可以用简单的方法做到这一点:

string pathToHTMLFile = @"C:\temp\someFile.html";
string htmlString = File.ReadAllText(pathToHTMLFile);

或者您可以使用 FileStream/StreamReader 将其流式传输:

using (FileStream fs = File.Open(pathToHTMLFile, FileMode.Open, FileAccess.ReadWrite))
{
    using (StreamReader sr = new StreamReader(fs))
    {
        htmlString = sr.ReadToEnd();
    }
}

后一种方法允许您打开文件,同时仍允许其他人对该文件执行读/写操作。我无法想象 HTML 文件会很大,但它具有流式传输文件的额外好处,而不是像第一种方法那样将其捕获为一个大块。

于 2018-11-20T00:50:41.757 回答
0
var htmlText = System.IO.File.ReadAllText(@"C:/filename.html");

如果文件在应用程序根目录下,用户如下

var htmlText = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath(@"~/filename.html"));
于 2020-11-16T16:45:50.933 回答