I would like to use a SQL query on a CSV file using C#. There is something like this for java here. Is there anything like this for c#?
You can use the appropriate OLE DB provider to query the text file. You can find the query string here:
Textfile Connection String Samples
You can use ODBC to run a query against a CSV File :
// using System.Data.Odbc;
string strConn = @"Driver={Microsoft Text Driver (*.txt; *.csv)};" +
"Dbq=C:;Extensions=csv,txt";
OdbcConnection objCSV = new OdbcConnection(strConn);
objCSV.Open();
OdbcCommand oCmd = new OdbcCommand("select column1,column2 " +
"from THECSVFILE.CSV", objCSV);
OdbcDataReader oDR = oCmd.ExecuteReader();
while (oDR.Read())
{
// Do something
}
So, do you mean using Linq?
Something like one of these?
http://blogs.msdn.com/b/wriju/archive/2009/05/24/linq-to-csv-getting-data-the-way-you-want.aspx
http://blogs.msdn.com/b/ericwhite/archive/2008/09/30/linq-to-text-and-linq-to-csv.aspx
// need to add
// using System.Linq;
void Main()
{
var path = @"C:\myfile.csv";
string csv = System.IO.File.ReadAllText( path );
var array = csv.Split(new[]{","}, StringSplitOptions.RemoveEmptyEntries);
// Do the mapping with your databinding object
var personArray = array.Select(p => new Person { Name = p});
// You need to have this DataContext defined somewhere, for instance using LinqToSql
using(var context = new PersonDataContext()){
context.InsertAllOnSubmit(personArray);
context.SubmitChanges();
}
}
// Imagine this class is one of linqToSql class
public class Person{
public string Name {get;set;}
}
You can use Openrowsets .
Enable SQL Ad Hoc/Openrowset in SQL configuration first. Once enabled you'll be able to connect your SQL Server Managerment studio and query Excel and comma delimited files.
Your queries will look something like:
SELECT * FROM OPENROWSET('MSDASQL','Driver={Microsoft Text Driver (*.txt; *.csv)};DefaultDir={your path}','SELECT * FROM ypurtextfile.csv')
You can use these queries in your C# code just like you query any other tables. Just check with your manager that he's ok with you enabling ad hoc on the SQL Server