C# 在.Net Compact Framework中将文件内容读取为字符串
我正在使用.net compact framework 2.0为移动设备开发一个应用程序。我试图将文件的内容加载到字符串对象,但不知何故我无法完成。C# 在.Net Compact Framework中将文件内容读取为字符串,c#,.net,compact-framework,C#,.net,Compact Framework,我正在使用.net compact framework 2.0为移动设备开发一个应用程序。我试图将文件的内容加载到字符串对象,但不知何故我无法完成。System.IO.StreamReader类中没有ReadToEnd()方法。是否还有其他类提供此功能?您在寻找什么 StringBuilder sb = new StringBuilder(); using (StreamReader sr = new StreamReader("TestFile.txt")) { String lin
System.IO.StreamReader
类中没有ReadToEnd()
方法。是否还有其他类提供此功能?您在寻找什么
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();
还有一个问题,如果您愿意将其分解为一行一行的数组。我认为紧凑框架不支持file.ReadAllText。请尝试改用此streamreader方法 这是一个VB示例,但很容易翻译成C# ReadLine没有更多行可读取时返回null。如果需要,可以将其附加到字符串缓冲区
string text = string.Empty;
using (StreamReader streamReader = new StreamReader(filePath, Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
另一种选择:
string[] lines = File.ReadAllLines("file.txt");
简单 请发布到目前为止的代码。我不知道为什么,但在File类中没有ReadAllText方法。错误:“System.IO.File”不包含“ReadAllText”的定义。你知道为什么吗?你在用新的关键词吗?创建文件实例和使用静态文件是两件不同的事情。我正在尝试使用您发布的静态方法。忙于阅读msdn并发现“注意:此方法在.NET Framework 2.0版中是新的。”将用另一个示例更新我的文章。效果很好。注意:我必须将AppendLine方法更改为Append方法。感谢您的时间。-1:
ReadAllText
未在.NET compact framework中实现,这正是问题所在。事实上,我猜我错了。然而,我有点困惑,因为OP中缺少了ReadToEnd
,但更简单的方法是将中间行包装在using语句中,这样就不必在阅读器上调用Close()
。让框架为您完成所有这些。正确。using不仅调用Close()
,还将调用Dispose()
,从而释放资源。