// Reading data from a text file.
string data = System.IO.File.ReadAllText( "TestData.txt" );
// Remove all commas that are in between quotes
data = System.Text.RegularExpressions.Regex.Replace( data, @"(\x22.*)(,)(.*\x22)", "$1$3" );
static DataSet ReadFile(string filePath)
{
string connectionString = String.Format(
@"Provider=Microsoft.Jet.OleDb.4.0;Data Source={0};Extended Properties=""Text;HDR=Yes;FMT=Delimited""",
System.IO.Path.GetDirectoryName(filePath));
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string command = String.Format(
@"SELECT * FROM {0}", System.IO.Path.GetFileName(filePath));
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command, conn))
{
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
// Loop through the data table and change names like "Doe,John" to "John Doe"
foreach (DataRow row in ds.Tables[0].Rows)
row[0] = Regex.Replace((string)row[0], @"([^,]*),([^,]*)", "$2 $1");
return ds;
}
}
private void button1_Click( object sender, EventArgs e )
{
string data = System.IO.File.ReadAllText("TestData.txt" );
data = System.Text.RegularExpressions.Regex.Replace( data, @"(\x22.*)(,)(.*\x22)", "$1$3" );
DataTable dt = CtreateTable( data );
dataGridView1.DataSource = dt;
}
private DataTable CtreateTable( string data )
{
string[] dataRows = data.Split( "\r\n".ToCharArray( ), StringSplitOptions.RemoveEmptyEntries );
DataTable dt = new DataTable( );
// First line has the column headders
foreach( string headder in dataRows[ 0 ].Split( ",".ToCharArray( ) ) )
{
dt.Columns.Add( new DataColumn( headder ) );
}
// Load the data
for( int idx = 1; idx < dataRows.Length; idx++)
{
string[] fields = dataRows[ idx ].Split( ",".ToCharArray( ) );
int column = 0;
DataRow dr = dt.NewRow( );
foreach( string field in fields )
{
dr[ column ] = field.Trim("\"".ToCharArray());
column++;
}
dt.Rows.Add( dr );
}
return dt;
}
string[] fields = dataRows[ idx ].Split( ",".ToCharArray( ) );
data = System.Text.RegularExpressions.Regex.Replace( data, @"(\x22.*)(,)(.*\x22)", "$1$3" )
string[] fields = dataRows[ idx ].Split( ",".ToCharArray( ) );
public System.Data.DataSet LoadData()
{
string path = @"C:\a.txt";
string fileContents = System.IO.File.ReadAllText(path);
fileContents = System.Text.RegularExpressions.Regex.Replace(fileContents, @"(\x22.*)(,)(.*\x22)", "$1$3");
System.IO.File.WriteAllText(path,fileContents.ToString());
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(path) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(path), conn);
System.Data.DataSet ds = new System.Data.DataSet("Temp");
adapter.Fill(ds);
return ds;
}
Open in new window