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?
Asked
Active
Viewed 9.5k times
50

Owen Blacker
- 4,117
- 2
- 33
- 70

lng
- 805
- 1
- 11
- 31
-
Please post the code you have so far. – Nick Heidke Jul 27 '11 at 20:33
4 Answers
100
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();
-
I don't know why but there is no ReadAllText method in File class. Error: 'System.IO.File' does not contain a definition for 'ReadAllText'. Any ideas why? – lng Jul 27 '11 at 20:53
-
Are you using the new keyword? Creating an instance of File and using the static File are two different things. – Jethro Jul 27 '11 at 20:57
-
-
Busy reading through msdn and found "Note: This method is new in the .NET Framework version 2.0." will update my post with another example. – Jethro Jul 27 '11 at 21:01
-
Works great. One note: i had to change AppendLine method for Append method. Thanks for your time. – lng Jul 27 '11 at 21:15
41
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!
-
1A little simpler would be wrapping your middle line in a using statement so you don't have to call `Close()` on your reader. Let the framework do all that for you. – krillgar Feb 19 '14 at 14:08
-
1Correct. Not only does the using call the `Close()`, but it will also call the `Dispose()`, which frees up resources. – krillgar Feb 21 '14 at 13:54
7
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.

Brad Christie
- 100,477
- 16
- 156
- 200
-
-1: `ReadAllText` is not implemented in the .NET compact framework, which is what the question was asking. – JohnD Feb 12 '14 at 17:51
-
Indeed, guess I was mistaken. However, I'm a little confused because `ReadToEnd` was missing according to OP, and yet it [exists in .net 2.0 compact](http://msdn.microsoft.com/en-us/library/System.IO.StreamReader_methods%28v=vs.80%29.aspx) – Brad Christie Feb 12 '14 at 20:02
3
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.

Nikki9696
- 6,260
- 1
- 28
- 23