-2

I have a text file with content as:

**************

Some text

**************

I want to read the text between **** in c#. How can I achieve the same in c sharp

adv12
  • 8,303
  • 2
  • 25
  • 45

3 Answers3

1

You could use ReadAllText to get the contents of the file, then Replace and Trim to remove the unwanted contents of the file:

var result = System.IO.File.ReadAllText(@"c:\path\to\file.txt")
    .Replace("*", string.Empty) // remove the asterisks
    .Trim(); // trim whitespace and newlines
Richard Ev
  • 51,030
  • 56
  • 187
  • 275
0

Here's how to read lines from a text file in general : What's the fastest way to read a text file line-by-line?

You can do this:

var lines = File.ReadAllLines(fileName);
int numLines = lines.Length;
for (int lineCounter = 1 /*discard the first*/;lineCounter<Length-1 /*discard the last*/;lineCounter++)

{
     Do whatever you want with lines[lineCounter]
}
Community
  • 1
  • 1
Robert Columbia
  • 6,180
  • 14
  • 30
  • 39
-1

If you know the **** count then this might help.

 string readContents; 
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{ 
    readContents = streamReader.ReadToEnd();
    int start = readContents.IndexOf("*****") + 1; 
    int end = readContents.LastIndexOf("*****", start); 
    string result = readContents.Substring(start, end - start);

}
Arun CM
  • 3,145
  • 2
  • 30
  • 34
  • That will also read the ******* lines – Martin Brown Jul 25 '16 at 16:38
  • @MartinBrown Code updated. Please check – Arun CM Jul 25 '16 at 17:29
  • Nope, still doesn't work. Suppose the file contains "*****\r\nSome Text\r\n*****". Variable `start` would end up being 1. LastIndex of then looks for "*****" in the string ending at 1. ie it looks for "*****" in "*". `end` then becomes -1 making substring fail. – Martin Brown Jul 26 '16 at 15:11