2015-02-24 82 views
0

我正在将文本文件读入程序(它们是Unicode中的代码,输出必须是utf-8)。下面的代码适用于较小的代码(约150行,其中行只有一个字),但是当我在较大的文件上使用它时(例如20.000行,仍然只有一行代码),程序需要半分钟完成任务。我应该写新的代码,还是有一种方法来优化?非常慢的StreamReader用于中等大小的文件。

int next; 
string storage = ""; 
using (StreamReader sr = new StreamReader(path)) 
     { 
      while((next = sr.Read()) != -1) 
      { 
       storage += Char.ConvertFromUtf32(next); 
      } 
      sr.Close(); 
     } 
+0

是:StreamReader.ReadToEnd()。请参阅https://msdn.microsoft.com/en-us/library/system.io.streamreader.readtoend(v=vs.110).aspx – 2015-02-24 07:37:26

+0

我使用新的sr(path,Encoding.Unicode),然后收到不仅仅是int通过99999999提高了复杂度。感谢球员们的答案,请关闭这个线程。 – Offa 2015-02-24 07:43:24

+0

使用Filehelpers.net http://filehelpers.sourceforge.net/ – Amit 2015-02-24 07:54:23

回答

3

使用StringBuilder而不是字符串:

int next; 
StringBuilder storage = new StringBuilder(); 
using (StreamReader sr = new StreamReader(path)) { 
    while ((next = sr.Read()) != -1) { 
     storage.Append(Char.ConvertFromUtf32(next)); 
    } 
    sr.Close(); 
} 
string result = storage.ToString(); 
0

所以,一切都开始真正顺利,当我用不同的StreamReader工作, using (StreamReader sr = new StreamReader(path, Encoding.Unicode)) 这一点,让我得到正确格式化字符串,而不是int,指示字符,这提高了A LOT的速度。