SoFunction
Updated on 2025-03-06

C# database and TXT import and export example


     private void button1_Click(object sender, EventArgs e)        
     {            
     if (() == )  
     {         
     using (FileStream fs = ()) 
     {              
     using (StreamReader sr = new StreamReader(fs, ("GB2312")))   
     {
//<span style="color:#3333ff;">System encoding ("GB2312") is required,
Otherwise, the name in string name = arr[0] is garbled</span>                                                                                                                                                                                                                                                    �
     Integrated Security=True;User Instance=True"))  
     {
//<span style="color:#3333ff;">DataDirectory refers to the absolute path of the database. You must add code in winForm, otherwise there is a problem with the database found by .NET. If you really don't understand, you can go to the blog park to see why</span>
     ();                    
     using (SqlCommand cmd = ())      
     {                         
     = "insert into T_Persons values(@Name,@Age)";
     string line = "";      
     while ((line = ()) != null)  
     {                
     string[] arr = ('|');      
     string name = arr[0];           
     int age = Convert.ToInt32(arr[1]); 
();//Don't forget
     (new SqlParameter("Name", name)); 
     (new SqlParameter("Age", age));  
     ();       
     }                    
     }                    
     }                   
     }               
     }               
("txt imports the database successfully!");
     }               
     }        
     private void button2_Click(object sender, EventArgs e)    
     {            
     if (() == )     
     {                 
     using (FileStream fs = ()) 
     {                  
     using (StreamWriter sw = new StreamWriter(fs, ("GB2312")))    
     {                     
     using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename='|DataDirectory|\';Integrated Security=True;User Instance=True"))                         
     {                         
     ();       
     using (SqlCommand cmd = ())     
     {                             
     = "select * from T_Persons";   
     using (SqlDataReader sdr = ())    
     {                                            
     while (())              
     {                              
     string name = (("Name"));
     int age = sdr.GetInt32(("Age"));  
     string line =name+"|"+age;                     
     (line);                          
     ();                       
     }                                     
     }                      
     }                 
     }                  
     }             
     }          
("Export data to txt successfully!");
     }        
     }
     </span>