A couple of useful helper classes can help with this class of problem. In the sample code below, the actual questions are anwered in the Main method. The first question is perhaps best answered by using a regular expression UNLESS you have a very large file to search. The regular expression requires the entire file to be held in memory. This is not normally a problem though. However, I present the following code to demonstrate how to do this only reading one line at once.
SmartEnumerableExt is a very simple extension method to make it easier to create a SmartEnumerable. These are based on original code by Jon Skeet: using System; using System. Collections; using System. Generic; using System. TXT"; File. WriteLine item. Marked as answer by liurong luo Monday, September 14, AM. You can use a StreamReader to read the file one line at a time reader. You will probably find it much easier to read in the entire file into some type of variable structure, such as an array.
Then you can more easily loop through the array to get the lines that you need. Hope this helps. ReadAllLines ; using the array "strfile", you can any index value.
Regards, S. ToString tr. Reading the entire file in one go is ok as long as the size of the file is small, its its too big then one massive string in memory is not a great idea.
This browser is no longer supported. Download Microsoft Edge More info. Contents Exit focus mode. Is this page helpful? Please rate your experience Yes No. Any additional feedback? The following examples require to add namespace using System.
It's super easy to read whole text file into string using static class File and its method File. Let's look under the hood of the previous example. Method File. ReadAllText is implemented similarly to the following code. The using statement ensures that method StreamReader.
0コメント