How do I search through a line in a text file and parse out only the lines specificed in a...

  • Thread starter Thread starter Justin_E
  • Start date Start date
J

Justin_E

Guest
Im currently writing a program that only writes lines of a text file specified by the user(which works when user manually enters line number), but now Im incorporating a barcode scanner. The barcode number that is referenced can be anywhere in the line of the text file but will vary txt file to txt file. The text file fields of each line are separated by | character. Here is an example:

KEY|Sequence|VariableData|Barcode_2D|Version

1|1|somedata|0000000001|Version_1

2|2|somedata|0000000002|Version_1

3|3|somedata|0000000003|Version_1

4|4|somedata|0000000004|Version_1

5|5|somedata|0000000005|Version_1

.........and so on.

I basically want to scan, lets say barcode 0000000002 thru 0000000004, into a txtbox and it will read and then write the whole line for records 2, 3 & 4. Like I said the bad part is that the barcode field varies txtfile to txtfile. So I need help with searching the header record and using that position to read all line but only parse out the ones specified by the txtboxes.

private void btnWriteToText_Click(object sender, EventArgs e)
{
DialogResult sa = saveFileDialog1.ShowDialog();
if (sa == DialogResult.OK)
{
//initialize print range text boxes
long firstNum = long.Parse(txtFirstNum.Text);
long lastNum = long.Parse(txtLastNum.Text);

string spoils = null;
string headerRec = null;


//initialize StreamReader and path to text file
StreamReader inputFile;
inputFile = File.OpenText(txtPath.Text);

//initialize StreamWriter and path to text file to be created
StreamWriter outputfile;
string path = saveFileDialog1.FileName;

//create text file or append text file
outputfile = CreateNewText_AppendText(ref headerRec, inputFile, path);

while (firstNum <= lastNum)
{
spoils = inputFile.ReadLine();
outputfile.WriteLine(ExtractLine(txtPath.Text, firstNum));
firstNum++;
}
outputfile.Close();
}
}
private static StreamWriter CreateNewText_AppendText(ref string headerRec, StreamReader inputFile, string path)
{
StreamWriter outputfile;
if (!File.Exists(path))
{
outputfile = File.CreateText(path);

//write first line of txt file = header record
headerRec = inputFile.ReadLine();
outputfile.WriteLine(headerRec);
}
else
{

outputfile = File.AppendText(path);
}
return outputfile;
}

static string ExtractLine(string fileName, long line)
{
string[] lines = File.ReadAllLines(fileName);
return lines[line + 0];
}

Continue reading...
 
Back
Top