Process:
1. When the button is clicked, the OpenFileDialog pops up
2. Determine if the suffix name is legal
3. Import the Database
Code in the button event:
1. Determine if the user selected the file.
2. Determine if the file selected by the user is txt
The first step, when the button is clicked, pops up the Select File box, Openfiledialogopenfiledialog ofd = new OpenFileDialog (); ofd. Filter = "File File |*.txt"; if (ofd. ShowDialog () = = DialogResult.OK) {if (ofd. Safefilename = = "*.txt") {This.txtFilePath.Text = ofd. filename;//ready to import data ImportData (OFD. FileName);}}
Code in ImportData:
*: This method can save the efficiency of opening the server connection, without having to perform a loop to open a connection.
1. Open reader stream, and develop the file encoding format, here is the native code, Encoding.default
2. Split the file with an agreed delimiter, which is used as a delimiter
3. Splicing SQL statements inserted into the database
4. Execute the SQL code.
private void ImportData (String Path) {String temp = string. Empty; File.readalltext (Path); The using (StreamReader reader = new StreamReader (path,encoding.default))//Specifies the encoding format, which is garbled if the specified file encoding format is not the same { Reader. ReadLine (); String connstr = configurationmanager.connectionstrings["Sqlconfig"]. ConnectionString; using (SqlConnection conn = new SqlConnection (CONNSTR)) {Conn. Open (); using (SqlCommand cmd = new SqlCommand (sql,conn)) using (SqlCommand cmd = conn. CreateCommand ()) {while (!string. IsNullOrEmpty (temp = reader. ReadLine ())) {var ss = Temp. Split (', '); , for the contract delimiter, the current SS is stored in an array of string sql = String that has been split. Format ("INSERT into tblstudent (Stuname,stusex,stubirthdate,stuphone) VALUES ({0},{1},{2},{3},{4})", Ss[0],SS[1], ss[2], ss[3]); Splicing SQL statements, numeric types require + ' Conn. Open (); Cmd.commandtext = SQL; Cmd. ExecuteNonQuery (); }//end while}//end SqlCommand}//end SqlConnection}//end StreamReader }
c/s read data from file (TXT) into database