Reading large text files with streams in C#

后端 未结 11 1665
野的像风
野的像风 2020-11-22 08:28

I\'ve got the lovely task of working out how to handle large files being loaded into our application\'s script editor (it\'s like VBA for our internal product for quick macr

11条回答
  •  死守一世寂寞
    2020-11-22 09:20

    Have a look at the following code snippet. You have mentioned Most files will be 30-40 MB. This claims to read 180 MB in 1.4 seconds on an Intel Quad Core:

    private int _bufferSize = 16384;
    
    private void ReadFile(string filename)
    {
        StringBuilder stringBuilder = new StringBuilder();
        FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
    
        using (StreamReader streamReader = new StreamReader(fileStream))
        {
            char[] fileContents = new char[_bufferSize];
            int charsRead = streamReader.Read(fileContents, 0, _bufferSize);
    
            // Can't do much with 0 bytes
            if (charsRead == 0)
                throw new Exception("File is 0 bytes");
    
            while (charsRead > 0)
            {
                stringBuilder.Append(fileContents);
                charsRead = streamReader.Read(fileContents, 0, _bufferSize);
            }
        }
    }
    

    Original Article

提交回复
热议问题