将一个HTML文件读入到内存中的字符串变量中

46

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

类似于这样的一些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>
8个回答

69

4
在读取文件之前,请确保检查文件是否存在。 :) - TGarrett
HAP替我完成了它! - Harold_Finch

25

使用System.IO.File.ReadAllText(fileName)方法


19
string html = File.ReadAllText(path);

13

这已经大部分都讲到了,但我有一个补充,因为之前的代码示例引发了一个问题。

Dim strHTML as String = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/folder/filename.html"))

5
使用 File.ReadAllText(path_to_file) 读取文件。

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文件会很大,但它具有流式传输文件的附加好处,而不像第一种方法一样捕获为一个大块。


这种后一种方法允许你在打开文件的同时,仍然允许其他人对文件执行读写操作。你是在暗示第一种方法禁止其他人对文件执行读取操作吗?因为我不这样认为。 - om-ha
等待您的回复 @vapcguy - om-ha
1
@om-ha,我并不是想暗示什么 - 老实说,我从未在执行File.ReadAllText时同时测试过读写操作。但是,我已经测试过多种后面的代码块组合。我只是想将其描述为代码中最后一个块的内容,因为有各种可以与FileModeFileAccess一起使用的选项实际上并不起作用,而你可能认为它们会起作用。 - vapcguy

4
您想进行什么样的处理?您可以使用XmlDocument doc = new XmlDocument();,然后跟上doc.Load(filename)。然后可以在内存中解析XML文档。
点击这里了解更多关于XmlDocument的信息:

1
var htmlText = System.IO.File.ReadAllText(@"C:/filename.html");

如果文件在应用程序根目录中,则使用以下用户

var htmlText = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath(@"~/filename.html"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接