在.Net Compact Framework中将文件内容读取为字符串

时间:2011-07-27 20:31:53

标签: c# .net compact-framework

我正在使用.net compact framework 2.0为移动设备开发应用程序。我试图将文件的内容加载到字符串对象,但不知怎的,我无法完成它。 ReadToEnd()类中没有System.IO.StreamReader方法。是否有另一个类提供此功能?

4 个答案:

答案 0 :(得分:97)

StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("TestFile.txt")) 
{
    String line;
    // Read and display lines from the file until the end of 
    // the file is reached.
    while ((line = sr.ReadLine()) != null) 
    {
        sb.AppendLine(line);
    }
}
string allines = sb.ToString();

答案 1 :(得分:41)

string text = string.Empty;
using (StreamReader streamReader = new StreamReader(filePath, Encoding.UTF8))
{            
    text = streamReader.ReadToEnd();
}

另一种选择:

string[] lines = File.ReadAllLines("file.txt");

https://gist.github.com/paulodiogo/9134300

简单!

答案 2 :(得分:7)

File.ReadAllText(file)你在寻找什么?

还有File.ReadAllLines(file)如果你喜欢它逐行分解成数组。

答案 3 :(得分:3)

我不认为紧凑的Framework支持file.ReadAllText。请尝试使用此streamreader方法。

http://msdn.microsoft.com/en-us/library/aa446542.aspx#netcfperf_topic039

这是一个VB示例,但很容易转换为C# ReadLine在没有更多行要读取时返回null。如果需要,可以将它附加到字符串缓冲区。