Hi
I want to know the code for reading a .txt file present in my system and then insert the text into the database.
Eg:The text in .txt file is "FromDate|Todate|Reason for leave"
Now i want this text to insert into databasetables with respect to thier fields
Kirtan PatelPosted Oct 30, 2008, 3:08 AM
Here is Coding
in Which There is Function i have made For Fetching Data From Data.txt File
In Which first File is Read trough Stream Reader and the Data From File ( ie text is Stored to String Variable )
Then We are spiting that String by Delimiter '|' and Save Separate data into separate String array Variables ( ie x[0],x[1],x[3])
and Assigning those to our globle variables ( FromDate , ToDate , Reason)
Then Using those Globle Variable to build out SQL Statement of Insertin Data into Data
and Done !!!!!!!!!!!!!! :)
you have to import 2 Namespaces that is
System.IO; and System.Data.SqlClient ;
Here is Code i have coded
public partial class Form1 : Form
{
SqlCommand comm;
SqlConnection con;
String FromDate, ToDate, Reason;
String constr = @"Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\db1.mdf;Integrated Security=True;User Instance=True";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//FetchDataFrom File And Assing to Variables Befor inserting
FetchDataFromFile();
//Connect To Data Base and Insert That FEtched Data To Database
con = new SqlConnection(constr);
con.Open();
comm = new SqlCommand();
comm.Connection = con;
comm.CommandText = "INSERT INTO data(FromDate,ToDate,Reason) values('" + FromDate + "','" + ToDate + "','" + Reason + "')";
comm.ExecuteNonQuery();
con.Close();
}
public void FetchDataFromFile()
{
String pathoftxtFile = Environment.CurrentDirectory + @"\data.txt";
StreamReader sr = new StreamReader(pathoftxtFile);
String dataoftxtFile = sr.ReadToEnd();
sr.Close();
String[] x = new String[3];
x = dataoftxtFile.Split('|');
FromDate = x[0];
ToDate = x[1];
Reason = x[2];
}
}
Happy Coding :)