如何阅读冗长的文本文件?

Afn*_*hir 1 c# optimization file-read

如果你有一个包含很多条目的大文本文件,你必须得到它们并将它们保存到List怎么办?有更快的方法来做到这一点,而不是像我的代码那样传统方式

    /// <summary>
    /// Reads Data from the given path
    /// </summary>
    /// <param name="path">Path of the File to read</param>
    public void Read(string path)
    {
        try
        {
            FileStream file = new FileStream(path, FileMode.Open);
            StreamReader reader = new StreamReader(file);
            string line;

            while ((line = reader.ReadLine()) != null)
            {                
                myList.Add(line);
                System.Windows.Forms.Application.DoEvents();
            }
            reader.Close();
            file.Close();
        }
        catch (Exception c)
        {
            MessageBox.Show(c.Message);
        }

    }
Run Code Online (Sandbox Code Playgroud)

Bro*_*ass 6

更快 - 可能不是,但更短?是:

myList.AddRange(File.ReadAllLines(path));
Run Code Online (Sandbox Code Playgroud)

此外,如果这是一个非常大的文件,你不应该在UI线程中进行加载,只需使用后台工作程序 - 这将使您无需调用Application.DoEvents()每一行,并且可能会比原始方法更快一些 - 尽管比较对于文件I/O的成本而言,节省的成本将是最小的,但您将获得更清晰的代码.