Hi All,
I want to store a csv file in sql table can u help me please..
If I am using excel file except csv it is working fine..
But when I am using csv file it is throwing exception "External table was not in correct format".
Please help me
Anish
Loading

Amit ChoudharyRank #145 · 15.8K reputationPosted Mar 26, 2010, 5:16 AM EDT
use following code to read text csv file and fetch the data into dataset:
In this code The method GetMyCSVFileData() is used to read the .CSV file. This function read the Mycsvfile.txt file and store the data into the dataset. We can get the data from dataset.
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
DataSet myDataSet = GetMyCSVFileData();
foreach (DataColumn MyDataColumn in myDataSet.Tables["MyDataTable"].Columns)
{
Console.Write("{0,-20}", MyDataColumn.ColumnName);
}
Console.WriteLine();
foreach (DataRow MyDataRow in myDataSet.Tables["MyDataTable"].Rows)
{
foreach (DataColumn c in myDataSet.Tables["MyDataTable"].Columns)
{
Console.Write("{0,-20}", MyDataRow[c]);
}
Console.WriteLine();
}
}
private static DataSet GetMyCSVFileData()
{
string MystringLine;
string[] MystringArray;
char[] charArray = new char[] { ',' };
DataSet MyDataSet = new DataSet();
DataTable MyDataTable = MyDataSet.Tables.Add("TheData");
FileStream MyFileStrema = new FileStream("Mycsvfile.txt", FileMode.Open);
StreamReader MyStreamReader = new StreamReader(MyFileStrema);
MystringLine = MyStreamReader.ReadLine();
MystringArray = MystringLine.Split(charArray);
for (int i = 0; i <= MystringArray.GetUpperBound(0); i++)
{
MyDataTable.Columns.Add(MystringArray[i].Trim());
}
MystringLine = MyStreamReader.ReadLine();
while (MystringLine != null)
{
MystringArray = MystringLine.Split(charArray);
DataRow dr = MyDataTable.NewRow();
for (int i = 0; i <= MystringArray.GetUpperBound(0); i++)
{
dr[i] = MystringArray[i].Trim();
}
MyDataTable.Rows.Add(dr);
MystringLine = MyStreamReader.ReadLine();
}
MyStreamReader.Close();
return MyDataSet;
}
}
}
please mark as answer if it helps.
Sam HobbsRank #107 · 20.5K reputationPosted Mar 26, 2010, 9:03 AM EDT
Sushta Guthnar110 reputationPosted Mar 26, 2010, 10:45 AM EDT
Shusta
Anish Khan25 reputationPosted Mar 29, 2010, 4:39 AM EDT
Thanks for reply,
Your code are working fery fine...............
I Used GetMyCSVFileData(){} function to read data and store it in to dataset.
And after that I used SQLBulkCopy to store it into database table
It's very usefull code.
Thanks Again
Anish
Anish Khan25 reputationPosted Mar 29, 2010, 4:41 AM EDT
You can't understand....
See Amit's post.....
-------------
Anish