StreamReader does not read in carriage returns

c#, streamreader

Solution

You can use `StreamReader.ReadToEnd` instead of `StreamReader.ReadLine`.

// Cange this:
// StreamReader sr = new StreamReader("input.txt");
// String line = sr.ReadLine();

string line;
using (StreamReader sr = new StreamReader("input.txt"))
{
    line = sr.ReadToEnd();
}

The addition of the `using` block will make sure the input file is closed properly, as well.

Another alterantive would just be to use:

string line = File.ReadAllText("input.txt"); // Read the text in one line

`ReadLine` reads a single line from the file, and strips off the trailing carraige return and line feed characters.

`ReadToEnd` will read the entire file as a single string, and preserve those characters, allowing your `chop` method to work as written.

Problem

I have to write a console application for a computer course that I'm taking. The program reads text in from a file using StreamReader, splits the string into single words and saves them in a String array and then prints the words out backwards. Whenever there is a carriage return in the file, the file stops reading in the text. Could anyone help me with this? Here is the main program: ``` using System; using System.IO; using System.Text.RegularExpressions; namespace Assignment2 { class Program { public String[] chop(String input) { input = Regex.Replace(input, @"\s+", " "); input = input.Trim(); char[] stringSeparators = {' ', '\n', '\r'}; String[] words = input.Split(stringSeparators); return words; } static void Main(string[] args) { Program p = new Program(); StreamReader sr = new StreamReader("input.txt"); String line = sr.ReadLine(); String[] splitWords = p.chop(line); for (int i = 1; i <= splitWords.Length; i++) { Console.WriteLine(splitWords[splitWords.Length - i]); } Console.ReadLine(); } } } ``` And here is the file "input.txt": ``` This is the file you can use to provide input to your program and later on open it inside your program to process the input. ```

Original source