Which code segment should you use?

You need to read the entire contents of a file named Message.txt into a single string variable.
Which code segment should you use?

You need to read the entire contents of a file named Message.txt into a single string variable.
Which code segment should you use?

A.
string result = null;
StreamReader reader = new StreamReader(“Message.txt”);
result = reader.Read().ToString();

B.
string result = null;
StreamReader reader = new StreamReader(“Message.txt”);
result = reader.ReadToEnd();

C.
string result = string.Empty;
StreamReader reader = new StreamReader(“Message.txt”);
while (!reader.EndOfStream) {
result + = reader.ToString();
}

D.
string result = null;
StreamReader reader = new StreamReader(“Message.txt”);
result = reader.ReadLine();

Explanation:
Create a StreamReader based on the file and call the ReadToEnd() method to quickly read the entire file and return a string.
A & D does not read the entire file.
C calling ToString() on the reader will give a string representation of the stream and will not read from the stream.



Leave a Reply 1

Your email address will not be published. Required fields are marked *


seenagape

seenagape

Correct answer is B