我有一个生成纯文本文件的程序。结构(布局)总是相同的。示例:
文本文件:
LinkLabel
"Hello, this text will appear in a LinkLabel once it has been
added to the form. This text may not always cover more than one line. But will always be surrounded by quotation marks."
240, 780
因此,要解释该文件中发生了什么:
Control
Text
Location
当单击表单上的一个按钮,用户从OpenFileDialog对话框中打开其中一个文件时,我需要能够读取每一行。从顶部开始,我想检查它是什么控件,然后从第二行开始,我需要能够获取引号中的所有文本(不管是一行还是多行),在下一行(在结束引号之后),我需要提取位置(240,780).我想了几种方法来解决这个问题,但是当我把它写下来并付诸实施时,它就没有多大意义了,最后我想出了一些不起作用的方法。
以前有人这样做过吗?有没有人能提供任何帮助,建议或建议,我如何去做这件事?
我已经查找了CSV文件,但对于看起来如此简单的事情来说,这似乎太复杂了。
谢谢贾塞
发布于 2009-09-29 22:47:37
您可以使用正则表达式从文本中获取行:
MatchCollection lines = Regex.Matches(File.ReadAllText(fileName), @"(.+?)\r\n""([^""]+)""\r\n(\d+), (\d+)\r\n");
foreach (Match match in lines) {
string control = match.Groups[1].Value;
string text = match.Groups[2].Value;
int x = Int32.Parse(match.Groups[3].Value);
int y = Int32.Parse(match.Groups[4].Value);
Console.WriteLine("{0}, \"{1}\", {2}, {3}", control, text, x, y);
}
发布于 2009-09-29 22:43:45
我将尝试写下算法,以及解决这些问题的方法(在注释中):
// while not at end of file
// read control
// read line of text
// while last char in line is not "
// read line of text
// read location
试着编写一段代码来完成每条注释都说的话,这样你就能找到答案了。
HTH。
发布于 2009-09-29 22:52:49
您正在尝试实现一个解析器,最好的策略是将问题分成更小的部分。您需要一个TextReader
类,使您能够读取行。
应该将ReadControl
方法分为三种方法:ReadControlType
、ReadText
和ReadLocation
。每个方法只负责读取它应该读取的项,并将TextReader
保留在下一个方法可以拾取的位置。就像这样。
public Control ReadControl(TextReader reader)
{
string controlType = ReadControlType(reader);
string text = ReadText(reader);
Point location = ReadLocation(reader);
... return the control ...
}
当然,ReadText是最有趣的,因为它跨越多行。实际上,它是一个调用TextReader.ReadLine
的循环,直到该行以引号结尾为止:
private string ReadText(TextReader reader)
{
string text;
string line = reader.ReadLine();
text = line.Substring(1); // Strip first quotation mark.
while (!text.EndsWith("\"")) {
line = reader.ReadLine();
text += line;
}
return text.Substring(0, text.Length - 1); // Strip last quotation mark.
}
https://stackoverflow.com/questions/1496421
复制