You are in the process of creating a new application.
This new application has to be able to read all data from a text file.
What should you do?
 
A.
Use the following code: 
FileStream fs = new FileStream(“C:file.txt”, FileMode.Open);  
StreamReader sr = new StreamReader (fs); 
string data = sr.ReadToEnd (); 
sr.Close (); 
Console.WriteLine (data);
B.
Use the following code: 
FileStream fs = new FileStream(“C:file.txt”, FileMode.Open);  
string data = sr.ReadToEnd (); 
fs.Close (); 
Console.WriteLine (data);
C.
Use the following code: 
FileStream fs = new FileStream(“C:file.txt”, FileMode.Open);  
StringBuilder data = new StringBuilder(); 
string data; 
while (sr.Peek () > -1) 
data += sr.ReadLine (); 
sr.Close (); 
Console.WriteLine (data);
D.
Use the following code: 
FileStream fs = new FileStream(“C:file.txt”, FileMode.Open);  
StreamReader sr = new StreamReader (fs); 
StringBuilder data = new StringBuilder (); 
while (sr.Peek () > -1) 
data.Append (sr.ReadLine ()); 
sr.Close (); 
Console.WriteLine (data.ToString ());
Explanation:
The FileStream constructor accepts a string argument as the file path and a FileMode enumeration value.
The FileMode enumeration value indicates the file stream will be used, and includes the values
Append, Create, CreateNew, Open, and Truncate.
The FileMode.Open value indicates a file will be opened if existing, or else a FileNotFoundException object will be thrown.
A StreamReader object is instantiated using the FileStream object as input. The ReadToEnd method returns a string representing all data from that position to the end of the file.
There are two other read methods, ReadLine and ReadBlock. The ReadLine method returns a string representing all data from that position to the end of a line return.
The ReadBlock method takes a character array, offset value and total number of characters as arguments.
Like all streams, the StreamReader object has a Close method, which should be called after work is done with the stream.
The Console.WriteLine method is invoked to display the data to the console.
Incorrect Answers:
B: You should not use the code that does not specify the StreamReader class because the FileStream class does not contain a ReadToEnd method.
C: You should not use the code that specifies a string object when invoking the ReadLine method rather than a StringBuilder object. The string object is less efficient than StringBuilder objects when performing concatenation operations.
D: This code should not be used because it manually iterates through the file using the ReadLine method, whereas the ReadToEnd method is more efficient.
 
                
A
0
0