Hi,
I need to read lines from a .txt or .csv file (not sure yet of the extension) where the data is ';' delimited.
I will use the below code:
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
But what I need to know is, on each line I have 4 attributes seperates with ';' how can i read each attribute seperatly and save it in a string value?
Thank you in advance
Loading
VulpesPosted Apr 4, 2012, 9:18 AM
I also notice that you're now reading 3 rather than 4 attributes in each line and so your Console.WriteLine() needs adjustment.
Your while statement should now look like this:
sabinePosted Apr 4, 2012, 8:58 AM
Below is the code I'm using:
int counter = 0;
string readLine;
string accountName= "";
string contactFName = "";
string contactLName ="";
StreamReader tr = new StreamReader("text.txt");
// Read header
tr.ReadLine();
counter++;
while((readLine = tr.ReadLine()) != null)
{
tr.ReadLine();
readLine = readLine.Trim();
if (readLine == "") continue; // ignore blank lines
string[] items = readLine.Split(';');
accountName = items[0];
contactFName = items[1];
contactLName = items[2];
Console.WriteLine("attr1 = {0}, attr2 = {1}, attr3 = {2}, attr4 = {3}" + accountName + contactFName + contactLName);
counter++;
}
tr.Close();
In my files, I am having the header and two lines of data but the issue is that this code is reading only 1 line of data.
How can I make it loop on all the data lines?
Thank you again
VulpesPosted Mar 23, 2012, 7:37 AM