【问题标题】:How to delete line start with specific symbol # in text file如何删除文本文件中以特定符号#开头的行
【发布时间】:2012-09-29 11:38:22
【问题描述】:

我正在开发一个简单的应用程序,它选择文件并读取该文本文件,我想删除所有以 `#cmets 行开头的行,这是代码

 private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                OpenFileDialog fdlg = new OpenFileDialog();
                fdlg.Title = ".txt File Detector";
                fdlg.InitialDirectory = @"c:\";
                fdlg.Filter = "txt files (*.txt)|*.txt";
                fdlg.FilterIndex = 2;
                fdlg.RestoreDirectory = true;
                if (fdlg.ShowDialog() == DialogResult.OK)
                {
                    input = fdlg.FileName;
                    textBox1.Text = fdlg.FileName;
                }
            }
            catch (Exception eee)
            {
                MessageBox.Show(eee.ToString());
            }
            string taxt = File.ReadAllText(input);
            string[] lines = new string[100000];
            //string taxt = File.ReadAllText(input);
          while(  taxt != null)
            {

            int count = 0;

                if (taxt.Trim().StartsWith("#") != true)
                {

                    lines[count] = taxt;
                    richTextBox1.Text += lines.ToString();
                    count++;
                }        


            }

我也尝试将正则表达式用作分隔符,但这在以 # 开头的 cmets 行的正则表达式为:

"@^#" 删除这些 cmets 行后,我想存储在 arraylist 中

【问题讨论】:

    标签: .net regex c#-4.0 windows-forms-designer


    【解决方案1】:

    你的代码有很多问题:

    • 您正在将整个文件读入单个字符串,因此您实际上并没有在行上循环
    • taxt 不为空时,您正在循环,但从不更改其值
    • 您每次迭代都调用string[].ToString,原因不明

    你想要一些东西,比如:

    richTextBox1.Lines = File.ReadLines(input)
                             .Where(line => !line.TrimStart().StartsWith("#"))
                             .ToArray();
    

    但是,您不应该在 UI 线程中进行文件处理。你真的想在RichTextBox 中显示结果,还是只是为了调试?

    【讨论】:

    • 不,我想将此文件存储在数组中,而不是解析日期以获取特定信息,所以将其存储在数组或数组列表中好还是我应该使用其他结构
    • @EmaanAbdulmajeed:好吧,假设您可以一次处理一行,我会在加载文件时使用 LINQ 进行所有解析等。听起来您可能应该问一个新问题,详细了解您在大局中真正想要实现的目标。
    猜你喜欢
    • 2018-05-13
    • 2015-05-04
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多