By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,364 Members | 1,272 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,364 IT Pros & Developers. It's quick & easy.

Reading Text File & Inserting into database table...

P: 1
Hello all,

I'm still learning about c# and I have a major function that I need to write (in a forms application), and I have no idea how to go about it. Here's the scenario:

I have a text file that contains all the data needed for a database table (MS SQL Server). I know the location and length of each field within the text file.

Can anyone explain to me (I know it may be quite involved) how I can read the text file, pull out the fields I need and place the data in a sql table?

length of each line is fixed, position of field is fixed. there will be N' number of line. each line is a record . each word in a line is a column value.

If you can help I will greatly appreciate it.

Thanks,

Sunil.
Sep 3 '08 #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 750
PRR
"I'm still learning about c# and I have a major function that I need to write (in a forms application), and I have no idea how to go about it. Here's the scenario:
I have a text file that contains all the data needed for a database table (MS SQL Server). I know the location and length of each field within the text file."

[HTML]
public void Read(string path)
{
path = @"C:\1.txt";
string line;

// Make a datatable to add your columns n later corresponding rows
DataTable dt = new DataTable();

DataColumn dc = new DataColumn("Field1");
dt.Columns.Add(dc);

dc = new DataColumn("Field2");
dt.Columns.Add(dc);
//Now ur columsn are added

List<string> ar = new List<string>();



if (File.Exists(path))
{
try
{
using (StreamReader sr = new StreamReader(path))
{

while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
ar.Add(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}//If path

int j = 0;// for 0th column...

DataRow dr=dt.NewRow();
//create a new row

for (int i = 0; i < ar.Count; i++)
{

dr[j] = ar[i];

j++;

if (j == 2)// j==2 .. here 2 is number of columns.. If one row is filled up
// j should become 0 ... and row should be added..
{
j = 0;
dt.Rows.Add(dr);
dr = dt.NewRow();
}
}

foreach (DataRow dr1 in dt.Rows)
{
Console.WriteLine(dr1[0].ToString()+" "+dr1[1].ToString());
}

/* C:\1.txt Contains:
*New YOrk
*1
* London
* 2
* Paris
* 3
*/
}
[/HTML]


I have put everything in one function.. try putting them in different function
also u need this namespaces..
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Data;
Sep 4 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.