NET C# 多文件导入


 

 

 

 private void button2_Click(object sender, EventArgs e)//多文件导入事件
        {
            if (folderb.ShowDialog() != DialogResult.OK)  //  打开对话框
            {
            }
            else {

                using (SqlConnection sqlcon = new SqlConnection("data source=.;database=csstsale;user=sa ;pwd=csst")) //建立数据库sqlconnection 对象
                {
                    sqlcon.Open();  //打开数据库

                    using (SqlCommand cmd = sqlcon.CreateCommand())  //建立数据库sqlcommand对象
                    {
                        cmd.CommandText = "insert into inputfile (name,age)values(@username,@age)";  //指定Commandtext对象
                        string path = folderb.SelectedPath;  //用string path来存取打开文件夹的路劲
                        string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);// 的搜索path目录下后缀为txt的文件
                        foreach (string file in files)//遍历这个files
                        {
                            string filename = Path.GetFileNameWithoutExtension(file);  //读取这个文件名
                            string[] lines = File.ReadAllLines(file,Encoding.Default);   //用readalllines方法读取file文件所有的行  ,文件小的情况用这个方法 ,否则用filestream

//编码默认是utf-8
                              foreach (string line in lines)    //遍历每一行                 

                                 {
                                if (line.IndexOf('-') <= 0)  //判断是不是有这个符号 如果没有就不能分割开来 返回
                                {
                                    MessageBox.Show("文件格式有问题。");
                                    return;
                                }
                                else {
                                string[] strs = line.Split('-');  分割每行的用-隔开的
                             
                                 string name = strs[0];  //第一部分是name
                                 string age = strs[1];//第二个拆分的是年龄
                                cmd.Parameters.Clear(); //清除parmeters变量
                                cmd.Parameters.Add(new SqlParameter("username", name)); //添加变量
                                cmd.Parameters.Add(new SqlParameter("age", age));
                                cmd.ExecuteNonQuery(); //执行。。。。

 

                            }


                        }
                      
                    }
                        sqlcon.Close();
                    }
                }
            }
        }

 


你可能感兴趣的:(数据库,windows,.net,String,File,Path,phone)