0

对不起,奇怪的标题,我想不出更好的了!

无论如何,我正在编写一个程序(Windows Forms App),它读取一个固定宽度的文件,从用户输入中收集字段长度,然后它应该以不同的颜色显示文件第一行的每一列... 你懂我的意思吗?它基本上是使用颜色来区分固定宽度文件中的不同字段。

我想问的是最好的方法是什么?因为我遇到了很多麻烦,而且当我知道有更好的解决方案时,我不断地遇到问题并实施令人作呕的解决方案。

显然你不必给我一个完整的程序,只是一些更好的方法来解决这个问题 - 因为我的解决方案太可怕了。

谢谢大家!

4

1 回答 1

1

我会使用RichTextBox。这有一个简单的方法来改变文本的颜色。这是一个示例,其中我有 3 个来自用户的输入,说明每列的宽度。然后它读入一个文件并适当地为宽度着色。希望这会给你更多的想法。

public partial class Form1 : Form
{
  public Form1()
  {
     InitializeComponent();
     ReadFile();
  }

  private void ReadFile()
  {
     // Assumes there are 3 columns (and 3 input values from the user)
     string[] lines_in_file = File.ReadAllLines(@"C:\Temp\FixedWidth.txt");
     foreach (string line in lines_in_file)
     {
        int offset = 0;
        int column_width = (int)ColumnWidth1NumericUpDown.Value;
        // Set the color for the first column
        richTextBox1.SelectionColor = Color.Khaki;
        richTextBox1.AppendText(line.Substring(offset, column_width));
        offset += column_width;

        column_width = (int)ColumnWidth2NumericUpDown.Value;
        // Set the color for the second column
        richTextBox1.SelectionColor = Color.HotPink;
        richTextBox1.AppendText(line.Substring(offset, column_width));
        offset += column_width;

        column_width = (int)ColumnWidth3NumericUpDown.Value;
        // Make sure we dont try to substring incorrectly
        column_width = (line.Length - offset < column_width) ?
            line.Length - offset : column_width; 
        // Set the color for the third column
        richTextBox1.SelectionColor = Color.MediumSeaGreen;
        richTextBox1.AppendText(line.Substring(offset, column_width));

        // Add newline
        richTextBox1.AppendText(Environment.NewLine);
     }
  }
}
于 2011-03-22T13:14:23.517 回答