I have tried this code for that in which it displays a result that neglects the first row. To include first row also what should i have to do?
My samplecsv.txt file is as below.
2,10.100.10.12,Murali,BB-CC-00-11-22-33,CC-DD-11-AA-00-BB
3,10.100.100.89,vaishnavi,AA-00-00-00-00-00,44-00-00-00-00-01
4,10.100.10.12,Murali,BB-CC-00-11-22-33,CC-DD-11-AA-00-BB
5,10.100.100.89,vaishnavi,AA-00-00-00-00-00,44-00-00-00-00-01
6,10.100.10.12,Murali,BB-CC-00-11-22-33,CC-DD-11-AA-00-BB
7,10.100.100.89,vaishnavi,AA-00-00-00-00-00,44-00-00-00-00-01
8,10.100.10.12,Murali,BB-CC-00-11-22-33,CC-DD-11-AA-00-BB
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=DEV-CHE-VRAN-01;Initial Catalog=SolarWindsOrion;Integrated Security=True");
StreamReader sr = new StreamReader("C:\\samplecsv.txt");
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "task2";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
MessageBox.Show("Inserted Successfully");
bc.Close();
con.Close();
}
After Executing the above program, i got the result as follows.
3 10.100.100.89 vaishnavi AA-00-00-00-00-00 44-00-00-00-00-01
4 10.100.10.12 Murali BB-CC-00-11-22-33 CC-DD-11-AA-00-BB
5 10.100.100.89 vaishnavi AA-00-00-00-00-00 44-00-00-00-00-01
6 10.100.10.12 Murali BB-CC-00-11-22-33 CC-DD-11-AA-00-BB
7 10.100.100.89 vaishnavi AA-00-00-00-00-00 44-00-00-00-00-01
Help me to resolve this issue..
Jignesh TrivediPosted Mar 31, 2014, 8:10 AM
hi,
try
StreamReader sr = new StreamReader("C:\\samplecsv.txt");
string[] lines = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
string line = lines[0];
string[] value = line.Split(',');
DataTable dt1 = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt1.Columns.Add(new DataColumn(dc));
}
foreach(var newLine in lines)
{
value = newLine.Split(',');
if (value.Length == dt1.Columns.Count)
{
row = dt1.NewRow();
row.ItemArray = value;
dt1.Rows.Add(row);
}
}
hope this will help you.
Vaishnavi RangamaniPosted Apr 1, 2014, 7:32 AM
Jignesh TrivediPosted Apr 1, 2014, 12:21 AM
hi,
StreamReader.ReadLine() function returns (reads) a line of character from the current stream upto the line feed ("\n").
this function return null when the end of the input stream is reached.
you are also call this function out side of while loop... so it not working..
hope you understand...
Vaishnavi RangamaniPosted Mar 31, 2014, 8:16 AM