Reading file content to string in .Net Compact Framework
C#.NetCompact FrameworkC# Problem Overview
I am developing an application for mobile devices with the .net compact framework 2.0. I am trying to load a file's content to a string object, but somehow I can't get it done. There is no ReadToEnd()
method in the System.IO.StreamReader
class. Is there another class that provides this functionality?
C# Solutions
Solution 1 - C#
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();
Solution 2 - C#
string text = string.Empty;
using (StreamReader streamReader = new StreamReader(filePath, Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
Another option:
string[] lines = File.ReadAllLines("file.txt");
https://gist.github.com/paulodiogo/9134300
Simple!
Solution 3 - C#
File.ReadAllText(file)
what you're looking for?
There's also File.ReadAllLines(file)
if you prefer it broken down in to an array by line.
Solution 4 - C#
I don't think file.ReadAllText is supported in the compact Framework. Try using this streamreader method instead.
http://msdn.microsoft.com/en-us/library/aa446542.aspx#netcfperf_topic039
It's a VB example, but pretty easy to translate to C# ReadLine returns null when it has no more lines to read. You can append it to a string buffer if you want.