我在 C# 中将本地文件读入字符串时遇到问题。
到目前为止,这是我想到的:
string file = @"C:\script_test\{5461EC8C-89E6-40D1-8525-774340083829}.html";
using (StreamReader reader = new StreamReader(file))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
textBox1.Text += line.ToString();
}
}
这似乎是唯一有效的解决方案。
我尝试了一些其他建议的读取文件的方法,例如:
string file = @"C:\script_test\{5461EC8C-89E6-40D1-8525-774340083829}.html";
string html = File.ReadAllText(file).ToString();
textBox1.Text += html;
但它并没有按预期工作。
这是我要读取的文件的前几行:
正如你所看到的,它有一些时髦的角色,老实说,我不知道这是否是这种奇怪行为的原因。
但在第一种情况下,代码似乎跳过了这些行,仅打印“Office Communicator 生成的文档...”
如果您可以使用 API 或 SDK,甚至有您尝试阅读的格式的描述,那么您的任务会更容易。然而,二进制格式看起来并没有那么复杂,并且带有一个十六进制查看器 https://i.stack.imgur.com/X3f7M.png安装我到目前为止已经从您提供的示例中获取了 html。
要解析非文本文件,您可以回退到二进制阅读器 https://msdn.microsoft.com/en-us/library/system.io.binaryreader(v=vs.110).aspx然后使用其中之一读取方法 https://msdn.microsoft.com/en-us/library/system.io.binaryreader_methods(v=vs.110).aspx从字节流中读取正确的类型。我用了ReadByte https://msdn.microsoft.com/en-us/library/system.io.binaryreader.readbyte(v=vs.110).aspx and 读Int32 https://msdn.microsoft.com/en-us/library/system.io.binaryreader.readint32(v=vs.110).aspx。请注意该方法的描述中如何解释读取了多少字节。当您尝试破译您的文件时,这会变得很方便。
private string ParseHist(string file)
{
using (var f = File.Open(file, FileMode.Open))
{
using (var br = new BinaryReader(f))
{
// read 4 bytes as an int
var first = br.ReadInt32();
// read integer / zero ended byte arrays as string
var lead = br.ReadInt32();
// until we have 4 zero bytes
while (lead != 0)
{
var user = ParseString(br);
Trace.Write(lead);
Trace.Write(":");
Trace.Write(user.Length);
Trace.Write(":");
Trace.WriteLine(user);
lead = br.ReadInt32();
// weird special case
if (lead == 2)
{
lead = br.ReadInt32();
}
}
// at the start of the html block
var htmllen = br.ReadInt32();
Trace.WriteLine(htmllen);
// parse the html
var html = ParseString(br);
Trace.Write(len);
Trace.Write(":");
Trace.Write(html.Length);
Trace.Write(":");
Trace.WriteLine(html);
// other structures follow, left unparsed
return html.ToString();
}
}
}
// a string seems to be ascii encoded and ends with a zero byte.
private static string ParseString(BinaryReader br)
{
var ch = br.ReadByte();
var sb = new StringBuilder();
while (ch != 0)
{
sb.Append((char)ch);
ch = br.ReadByte();
}
return sb.ToString();
}
您可以在 winform 应用程序中使用简单的解析逻辑,如下所示:
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.DocumentText = ParseHist(@"5461EC8C-89E6-40D1-8525-774340083829-Copia.html");
}
请记住,这不是防弹或推荐的方法,但它应该可以帮助您入门。对于无法很好解析的文件,您需要返回到十六进制查看器并找出哪些其他字节结构是新的或与您已有的不同。这不是我打算帮助你的事情,而是作为练习留给你去弄清楚。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)