Reading large text files with streams in C#

后端 未结 11 1669
野的像风
野的像风 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

    This should be enough to get you started.

    class Program
    {        
        static void Main(String[] args)
        {
            const int bufferSize = 1024;
    
            var sb = new StringBuilder();
            var buffer = new Char[bufferSize];
            var length = 0L;
            var totalRead = 0L;
            var count = bufferSize; 
    
            using (var sr = new StreamReader(@"C:\Temp\file.txt"))
            {
                length = sr.BaseStream.Length;               
                while (count > 0)
                {                    
                    count = sr.Read(buffer, 0, bufferSize);
                    sb.Append(buffer, 0, count);
                    totalRead += count;
                }                
            }
    
            Console.ReadKey();
        }
    }
    

提交回复
热议问题