如果我在磁盘上有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>
答案 0 :(得分:46)
使用File.ReadAllText传递文件位置作为参数。
但是,如果您真正的目标是解析HTML,那么我建议您使用Html Agility Pack。
答案 1 :(得分:16)
使用System.IO.File.ReadAllText(fileName)
答案 2 :(得分:12)
string html = File.ReadAllText(path);
答案 3 :(得分:10)
这已经被大部分覆盖了,但是当我遇到上述代码示例的问题时,还有一个补充。
Dim strHTML as String = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/folder/filename.html"))
答案 4 :(得分:5)
使用File.ReadAllText(path_to_file)
阅读
答案 5 :(得分:4)
你想做什么样的处理?您可以XmlDocument doc = new XmlDocument();
后跟doc.Load(filename)
。然后可以在内存中解析XML文档。
在此处阅读有关XmlDocument的更多信息:
答案 6 :(得分:0)
您可以通过简单的方式做到这一点:
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文件太大,但是它具有流式传输文件而不是像第一种方法那样将其捕获为一个大块的额外好处。
答案 7 :(得分:0)
var htmlText = System.IO.File.ReadAllText(@"C:/filename.html");
如果文件位于应用程序根目录下,则该用户位于以下
var htmlText = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath(@"~/filename.html"));