Help me with database connection.
I am trying to open a CSV file and store it in a bindingsource
i use a open file dialog to open point to the desired file and the problem i am running into is my catch says that the file can not be found. even though i know the path is correct.
are there any obvous problems with this code that i am missing
:portion of code that i use to create the OFD and filter for the CSV file
and return the datatable to the bindingsource
Code:
OpenFileDialog OFD_Invoice = new OpenFileDialog();
OFD_Invoice.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
OFD_Invoice.Filter = "Tab delmited (*.csv)|*.csv";
OFD_Invoice.FilterIndex = 1;
OFD_Invoice.FileName = "";
if (OFD_Invoice.ShowDialog() == DialogResult.OK)
{
string
csvpath = OFD_Invoice.FileName,
adapter = "SELECT F3 AS Name, SUM(F10) AS TotalPayments FROM [" + csvpath + "] GROUP BY F3";
Console.WriteLine(adapter);
FileInfo DataFile = new FileInfo(OFD_Invoice.FileName);
string path = DataFile.Directory.ToString();
invoicebindingsource.DataSource = ReadCSVFile(path, "ipass", adapter, "no");
dgv_invoice.DataSource = invoicebindingsource;
IS the sub that opens my CSV files
Code:
private DataTable ReadCSVFile(string path, string tablename, string adapter, string header)
{
try
{
System.Data.OleDb.OleDbConnection cnCSV = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + @";Extended Properties=""text;HDR=" + header + @";FMT=Delimited""");
System.Data.OleDb.OleDbDataAdapter daCSV = new System.Data.OleDb.OleDbDataAdapter(adapter, cnCSV);
DataTable dt = new DataTable(tablename);
daCSV.Fill(dt);
Refresh();
return dt;
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + Environment.NewLine + ex.Message);
Console.WriteLine(ex.ToString());
return null;
}//catch
}
Re: Help me with database connection.
You've chose some dodgy variable names for a start. "adapter" for a string containing SQL code?
Anyway, you are assigning the full path of the file to the 'csvpath' variable and then using that as the table name in your SQL code. You should be separating the path of the selected file into folder path and file name. The folder path is then the Data Source in your connection string and the file name is then the table name in your SQL code. When you use ADO.NET to read text files the folder is treated as the database and the files are treated as the tables. You open the connection to the folder, so to access a "table" you don't need to specify the full path.
I suggest that you use the IO.Path class to manipulate file and folder paths, e.g.
Code:
string filePath = ofd.FileName;
string folderPath = System.IO.Path.GetDirectoryName(filePath);
string fileName = System.IO.Path.GetFileName(filePath);