文本文件:
阿斯顿|12
周小川|14
东丰阁|15
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;
using System.Data.SqlClient;
namespace ADONet练习1
{
/// <summary>
/// CustomerImportExportWindow.xaml 的交互逻辑
/// </summary>
public partial class CustomerImportExportWindow : Window
{
public CustomerImportExportWindow()
{
InitializeComponent();
}
private void btnImport_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "文本文件|*.txt";
if (ofd.ShowDialog() != true)
{
return;
}
string filename = ofd.FileName;
//File.ReadLines是把文件一次读取到string集合中
//FileStream
//乱码发生在保存和读取的编码不一致的情况下
//File.ReadLines没有第二个参数的重载是采用UTF8编码
IEnumerable<string> lines = File.ReadLines(filename,Encoding.Default);
foreach (string line in lines)
{
//把“杨中科|18 ”按照|分割
string[] segs = line.Split('|',' ');//new string[]{"杨中科","18"};
string name = segs[0];
string age = segs[1];
SqlHelper.ExecuteNonQuery("Insert into T_Customer(Name,Age) values(@Name,@Age)",
new SqlParameter("@Name",name),
new SqlParameter("@Age", Convert.ToInt32(age)));
}
MessageBox.Show("导入成功!成功导入"+lines.Count()+"条数据!");
}
}
}