Hello:
I do a ReadLine on a text file and I need to split out the columns so I can populate a dataGrid. The data uses comma seperators. Reason I am not using Jet or ODBC is because it seems these two do not work on x64.
Below is my code, for now:
{
String line;
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("C:\\Test.txt");
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the lie to console window
Console.WriteLine(line);
//Read the next line
line = sr.ReadLine();
// Column1 = ____;
//Column2 = ____;
}
//close the file
sr.Close();
Console.ReadLine();
}
Loading
Kirtan PatelPosted Feb 28, 2010, 3:37 PM
Here is How to do ..the task u are doing ..by simple code .without any Stream Reader etc .
static void Main(string[] args)
{
string[] LinesInFile = File.ReadAllLines("C:\\Test.txt");
foreach (string line in LinesInFile)
{
if (line != "")
{
Console.WriteLine(line);
string[] columns = line.Split(',');
string column1 = columns[0];
string column2 = columns[1];
// and So on...
}
}
}
theLizardPosted Feb 28, 2010, 9:47 PM
string[] LinesInFile = File.ReadAllLines("C:\\Test.txt"); <--- is this not a type of CSV or am i just confused? an why would you use File.ReadAllLines to do this?
foreach (string line in LinesInFile)
{
if (line != "") //you would not need this if you did not read in empty lines to begin with.
{
Console.WriteLine(line);
string[] columns = line.Split(','); //e[e.Length-1].elements = l.Split(new char[] {','});
string column1 = columns[0]; //you would already have an array of lines (e) and columns (e[x].elements) why would you need these for? eat up more resources I guess.
string column2 = columns[1];
If this is the BEST solution for your issue, do you actually know what your issues are!GustavoPosted Feb 28, 2010, 4:13 PM
This is the BEST solution for my issue. After trying everything and posting like crazy... this is SUPER.
Its so much simpler and cleaner code.
Thank you, Thank you, Thank you.
GustavoPosted Feb 28, 2010, 3:40 PM
Coooool.... Thanks.