Reputation: 1964
What would be the best way to search a text file that looks like this..?
efee|| Nbr| Address| Name |Phone|City|State|Zip
abc ||455|gsgd |first last|gsg |fef |jk |0393
gjgj||jfj|ddg
|first last|fht |ree |hn |th ...more lines...
I started by reading in the file and all its contexts with a streamreader I was thinking to count the "|" and grab the text between the 5th and 6th using substring but i'm not sure how to do the count of the "|". Or if someone has a better idea I'm open to it. Tried something like this:
StreamReader file = new StreamReader(@"...");
string line;
int num=0;
while ((line = file.ReadLine()) != null)
{
for (int i = 1; i <= 6; i++)
{
if (line.Contains("|"))
{
num++;
}
}
int start = line.IndexOf("|");
int end = line.IndexOf("|");
string result = line.Substring(start, end - start - 1);
}
The text I want I beleive is always between the 5th and 6th "|"
Upvotes: 3
Views: 257
Reputation: 499062
For a delimited file you should use a parser - there is one in the Microsoft.VisualBasic.FileIO
namespace - the TextFieldParser
class, though you could also look at third-party libraries like the popular FileHelpers.
A simpler approach would be to use string.Split
on the |
character and getting the value in the corresponding index of the returned string[]
, however, if any of the fields are escaped and can validly contain |
internally, this will fail.
Upvotes: 1
Reputation: 726639
You can do it like this:
var res = File
.ReadLines(@"FileName.txt")
.Select(line => line.Split(new[]{'|'}, StringSplitOptions.None)[5])
.ToList();
This produces a List<strings>
from the file, where each string is the part of the corresponding line of the file taken from between the fifth and the sixth '|'
separator.
Upvotes: 2
Reputation: 13033
This should work
string txt = File.ReadAllText("file.txt");
string res = Regex.Match(txt, "\\|*?{5}(.+?)\\|", RegexOptions.Singleline).Result("$1");
Upvotes: 0
Reputation: 1784
You could split each line into an array:
while ((line = file.ReadLine()) != null)
{
var values = line.Split('|');
}
Upvotes: 0