[英]Read different chunks in text file in c#
我正在用可视C#构建表单应用程序。 我的问题是我需要阅读所有带红色下划线的列(如图所示),并跳过蓝色的列:
我不知道我应该使用readline还是readblock方法。 此外,程序将如何知道红色列何时结束以及如何转到下一个红色列。 我需要使用字符计数吗?
这是我当前的代码:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));
// constructor sr accesses streamreader class. In stream reader class we access method read to end
textBox1.Text = sr.ReadToEnd();
// fill textbox with this.
sr.Dispose();
}
}
非常抱歉,我是新手-非常感谢您的帮助。
看起来,两个非常简单的规则可以帮助处理这些文件:
1)第一列中有字符的行(不是空格)使您退出表模式。
2)具有相等和空格的组的行以表模式启动。
a)列宽由等号段的宽度定义
b)前一行通常给出列名
使用它,您可以为此文件格式创建一个常规解析器。 只需一次阅读一行,然后针对您阅读的每一行应用进入离开表的规则。 (如果需要标题名称,请保持单向)
编辑:添加了代码示例。 (问题是整个程序大部分由“第一行”编写)
using( StreamReader input = new StreamReader("somefile.txt") )
{
List<int> bounds = new List<int>();
for( string line = input.ReadLine(); line != null; line = input.ReadLine() )
{
if( line.Length > 0 && line[0] == '-' )
bounds.Clear();
if( Regex.IsMatch(line, "^ *=[ =]*$") ) // This is a column header
{
bounds.Clear();
for( int i = 1; i<line.Length; ++i )
if( line[i - 1] != line[i] )
bounds.Add(i);
}
else if( bounds.Count > 0 )
{
List<string> cells = new List<string>();
string padLine = line.PadRight(bounds[bounds.Count-1]);
for( int i=0; i<bounds.Count; i += 2 )
cells.Insert(i / 2, padLine.Substring(bounds[i], bounds[i+1]));
// retrieve data cells[7] (column 7) here and store elsewhere.
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.