6. Vote for the favorite |
At first, I used StreamReader to read text from the file. Card Reader = new StreamReader ("dialog box. Use OpenFile ()); TxtEditor. Text Reader. ReadToEnd (); However, I found that File. ReadAllText seems to simplify my code to line 1. But I think, if there are any differences between two? Or when should I use 1 more than others? TxtEditor. Text file. ReadAllText (dialog. FileName ); |
3. Accept the vote |
Is there any difference if you are using the ReadToEnd () method. The difference is that if you don't load the entire file into the memory, you can use the ReadLine () method of large files in the block for processing. Therefore, use File. ReadAllText () instead of ReadToEnd (), because it makes your code shorter and more readable. It also needs to take care of and properly handle resources as you may forget to make StreamReader (as you do in your clips ). |
Up to one vote |
If you use ReadToEnd, they are the same. Otherwise, StreamReader allows you to read the bytes at a time, perform some calculations with them, and then discard them as needed. For example, if you have a file that contains a list of 2000 numbers and you want to add them together, you can:
- Call File. ReadAllText to read all the content of a string, and then calculate the sum by parsing the string.
- Alternatively, you can create a StreamReader to read several bytes at a time and calculate the amount when you go.
The main difference between the two methods is short memory usage. After the payment, you have, you can leave and discard all the intermediate data at any time. In File. the ReadAllText method, in some cases, you have the entire file content in the memory, and the StreamReader method, you only have a few bytes, the value of the file content in the memory at any time. This may be a problem, according to the file size and calculation, you do. File. ReadAllText is convenient and quick. StreamReader is powerful, but more work. |