Skip to main content
 首页 » 编程设计

c#之提高 TextFile 的读取效率(更大的文件类型)

2024年02月23日15sxdcgaq8080

以下是我的代码,但一次不能处理超过 500 行。

需要在行尾加一个,,同时进行检测。我目前正在做的是将它们分成 2 个不同的文本框,然后通过复制粘贴保存我需要的文本框,但如果文件太大,应用程序似乎会挂起。

有人可以帮助我提高效率吗?非常感谢。

 private void button1_Click_1(object sender, EventArgs e) 
    { 
        if (openFileDialog1.ShowDialog() == DialogResult.Cancel) 
            return; 
 
        System.IO.StreamReader Reader = new System.IO.StreamReader(openFileDialog1.FileName); 
 
        //Create a filestream 
 
        FileStream fStr; 
 
        try 
        { 
            //Set filestream to the result of the pick of the user 
 
            fStr = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read); 
 
 
            //Create a streamreader, sr, to read the file 
 
            StreamReader sr = new StreamReader(fStr); 
 
            //While the end of the file has not been reached... 
 
            while (sr.Peek() >= 0) 
            { 
                //Create a 'line' that contains the current line of the textfile 
 
                string line = sr.ReadLine().ToLower(); 
 
                if (line.Contains("staff")) 
                { 
 
                    line += ","; //Add a , to the end of the line**Important** 
                    textBox1.Text += line + Environment.NewLine; 
                    releventcount += 1; 
                } 
                else 
                { 
                    line += ","; //Add a , to the end of the line**Important** 
                    textBox2.Text += line + Environment.NewLine; 
                    irreleventcount += 1; 
                } 
 
                label1.Text = "Relevent: "; 
                label2.Text = "Irrelevant: "; 
            } 
            //Close the file so other modules can access it 
            sr.Close(); 
            //If something goes wrong, tell the user 
        } 
        catch (Exception) 
        { 
 
            MessageBox.Show("Error opening file", "Check the CODE ! ~.~"); 
        } 
 
 
    } 

请您参考如下方法:

我不确定您最终要在这里完成什么。有几种更简洁的方法可以完成您当前代码正在做的事情,但它们不会显着提高阅读速度。

您代码中的瓶颈在于您要追加字符串。使用 StringBuilder这是个好建议,但您可以通过创建一个 List<string> 来做得更好然后调用string.Join在最后。例如:

if (openFileDialog1.ShowDialog() == DialogResult.Cancel) 
    return; 
List<string> staff = new List<string>(); 
List<string> other = new List<string>(); 
 
foreach (var line in File.ReadLines(openFileDialog1.FileName)) 
{ 
    line = line.ToLower(); 
    if (line.Contains("staff")) 
    { 
        staff.Add(line); 
    } 
    else 
    { 
        other.Add(line); 
    } 
} 
 
relevantcount = staff.Count; 
irrelevantCount = other.Count; 
 
textBox1.Text = string.Join(","+Environment.NewLine, staff); 
textBox2.Text = string.Join("."+Environment.NewLine, other); 

此外,您说您的代码一次只能处理 500 行。您的用户界面中是否有某些东西阻止它处理更多?当然,您显示的代码中没有任何内容具有如此低的限制。