I am stuck with a small problem. I need help here .... So, please help me if anybody having a solution for this.
I am having a no of csv files and each file is having two rows. Now what i want is, reading each file and writing the elements of each row from the csv files, into two fixed arrays.
The code i wrote is:
FolderBrowserDialog folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
string[] filesGot = Directory.GetFiles(folder.SelectedPath);
try
{
List listA = new List();
List listB = new List();
foreach (string fileRead in filesGot)
{
string[] datalines = File.ReadAllLines(fileRead);
foreach (string line in datalines)
{
string[] mycolumns = line.Split(',');
listA.Add(mycolumns[0]);
listB.Add(mycolumns[1]);
}
}
string[] firstlistA = listA.ToArray();
string[] firstlistB = listB.ToArray();
}
csharp beginnerPosted Jun 23, 2014, 2:30 PM
csharp beginnerPosted Jun 23, 2014, 2:28 PM
Farhan ShariffPosted Jun 23, 2014, 10:25 AM
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
// To list only csv files, we need to add this filter
openFileDialog.Filter = "|*.csv";
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
tbCSVPath1.Text = openFileDialog.FileName;
}
table1 = GetDataTabletFromCSVFile(tbCSVPath1.Text);
//Read elements into Array
List
// Classic version :-)
for( int a = 0 ; a < datatable1.Rows.Count ; a ++)
{
firstlistA.Add(table1.Rows[a]["Column Name"].ToString());
}
}
//Function to import csv file to Memory
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable table1 = new DataTable();
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn1 = new DataColumn(column);
datecolumn1.AllowDBNull = true;
table1.Columns.Add(datecolumn1);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
table1.Rows.Add(fieldData);
}
}
return table1;
}
Anupam SinghPosted Jun 23, 2014, 5:44 AM
if you have your csv file like :
then you are not going to face any issue using this code.
You might have any incorrect file if its not working for you.
csharp beginnerPosted Jun 23, 2014, 5:23 AM
Anupam SinghPosted Jun 23, 2014, 5:05 AM