Reading Text File & Inserting into database table...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ayyanki
    New Member
    • Sep 2008
    • 1

    Reading Text File & Inserting into database table...

    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.
  • PRR
    Recognized Expert Contributor
    • Dec 2007
    • 750

    #2
    "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("Fie ld1");
    dt.Columns.Add( dc);

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

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



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

    while ((line = sr.ReadLine()) != null)
    {
    Console.WriteLi ne(line);
    ar.Add(line);
    }
    }
    }
    catch (Exception e)
    {
    Console.WriteLi ne("The file could not be read:");
    Console.WriteLi ne(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.WriteLi ne(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.Collecti ons;
    using System.Collecti ons.Generic;
    using System.Data;

    Comment

    Working...