Question

i have following code and i tried everything mentioned on online and couldn't able to read data from text file.

string path=@"D:\New folder\abc.txt"
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);

string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + @";Extended Properties=""text;HDR=YES;FMT=TabDelimited""";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

excelConnection.Open();
OleDbCommand cmd = excelConnection.CreateCommand();
cmd.CommandText = String.Format("SELECT * FROM [{0}]", fileName);  
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();

DateTime UploadedDate = DateTime.Now;
DataTable sourceData = new DataTable();
sourceData.Load(dReader);
DataColumn col = new DataColumn("UploadedDateCol", typeof(DateTime));
col.DefaultValue = UploadedDate;
sourceData.Columns.Add(col);
int x = sourceData.Rows.Count;

always this x value is 0. my pc is 64 bit pc. Or else is there any other library that i can use for bulk upload.

My .txt file as below: these values are separated by tab or pipeline(|)

0421230424  3391542691  5295963551  2755344586  12345678
Was it helpful?

Solution 2

In order to overcome this problem defined details in Schema.ini file. if the file name is abc.txt then its need to create abc.ini file in same location.

 string iniFileMsg = "[" + newfileName + ".txt]";
 StreamWriter sw = new StreamWriter(newFilePath + "/schema.ini", false);
 sw.WriteLine(iniFileMsg);
 sw.WriteLine("Format=Delimited(|)");
 sw.WriteLine("ColNameHeader=True");
 sw.Flush();

If you have different coumns then its need to add as follows:

 List<string> columns = excelobj.GetCSVColumnNames(excelUploadedFullPath);
                //  sw.WriteLine("Col1=Phone Text Width 10");
for (int i = 0; i < columns.Count; i++)
{
   sw.WriteLine("Col" + (i + 1) + "=" + columns[i].Replace(" ", "_") + " Text Width 100");
}
sw.Flush();
sw.Close();

From GetCSVColumnNames() i got column names. after that i upload data as above method

OTHER TIPS

As far as tab delimited files are concerned, you should always have a look at the FileHelper library.

Don't reinvent the wheel, this library is very mature.

The FileHelpers are a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.

The idea is pretty simple:

You can strong type your flat file (fixed or delimited) simply describing a class that maps to each record and later read/write your file as an strong typed .NET array

The Library also has support for import/export data from differents storages like Excel, Access, SqlServer, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top