Reputation: 63
I know this is probably a newbie question but I need help with my first C# program. I need to extract some strings from a file. Every line looks like this:
630 FWTRGS782BT a-p 66.12.111.198
and need to only retrieve (it is a serial number):
FWTRGS782BT
I was thinking the correct way could to use line.Substring() but I really don't know how to retrieve it.
Actually every serial number starts by FG or FW, so it could may be possible to extract whenever I get a match with those first two letters and get up till the end of the string (or /t)?
Upvotes: 0
Views: 246
Reputation: 483
Here an example of how to read all serial numbers from a file
private List<string> GetAllSerialNumbersFromDocument(string pathToFile) //something like "C://folder/folder/file.txt"
{
List<string> serialNumbers = new List<string>(); //list where all serial numbers are stored
using (System.IO.StreamReader file = new StreamReader(pathToFile)) //Use 'using' because TextReader implements IDisposable
{
string line;
while ((line = file.ReadLine()) != null) //read all lines
{
serialNumbers.Add(GetSerialNumber(line)); //Get serial number of line and save it into list
}
}
return serialNumbers; //return all serial numbers
}
private string GetSerialNumber(string line)
{
var singleElements = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries); //split elements
return singleElements.First(x => x.StartsWith("FW") || x.StartsWith("FG")); //Get serial number
}
Upvotes: 2
Reputation: 2490
Try this:
string line = "630 FWTRGS782BT a-p 66.12.111.198";
var lineArr = line.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var requiredText = lineArr.Where(x => !string.IsNullOrEmpty(x) && x.StartsWith("FW") || x.StartsWith("FG"));
Upvotes: 2
Reputation: 16277
var input = "630 FWTRGS782BT a-p 66.12.111.198";
var output = input.Split( new char []{ ' ' },
StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(output[1]); //➙ FWTRGS782BT
Upvotes: 1