过滤C#中的特定行

KPS*_*KPS 2 c# text file

我搜索过但没有为我的项目找到可行的解决方案.我想要做的是打开一个文本文件,并仅过滤以"description"开头的行.

这只是我的文本文件中的一小部分示例:

interface Ethernet1/5
  description INFRA:TRUNK:myserver4
  switchport mode trunk
  switchport trunk native vlan 64
  spanning-tree mst pre-standard
  spanning-tree guard root
  udld aggressive
  no shutdown

 interface Ethernet1/6
  description INFRA:TRUNK:easyserver99
  switchport mode trunk
  switchport trunk native vlan 99
  spanning-tree mst pre-standard
  spanning-tree guard root
  udld aggressive
  no shutdown
Run Code Online (Sandbox Code Playgroud)

这是我现在使用的代码,但它没有完成工作.

private void scrapeConfig_Click(object sender, EventArgs e)

    {
    string textline;
    string description;

    //Open and read file
    System.IO.StreamReader objReader;
    objReader = new System.IO.StreamReader(Chosen_File);
    textBox1.Text = objReader.ReadToEnd();

    //Scrape for certain lines
    do
    {
    textline = objReader.ReadLine() + "\r\n";
    textBox1.Text = textline;
    } while (objReader.Peek() != -1);

    //Close
    objReader.Close();
}
Run Code Online (Sandbox Code Playgroud)

提前谢谢你的帮助!

Muh*_*han 9

var lines = File.ReadAllLines(filepath)
                .Select(l=>l.Trim())
                .Where(l=>l.StartsWith("description"));
textBox1.Text = String.Join(Environment.NewLine, lines);
Run Code Online (Sandbox Code Playgroud)

  • @KPS,你错过的是System.IO,我想. (2认同)