標籤:style blog color os io ar for 檔案 資料
1 using Microsoft.Win32; 2 using System; 3 using System.Collections.Generic; 4 using System.Data.SqlClient; 5 using System.IO; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows;10 using System.Windows.Controls;11 using System.Windows.Data;12 using System.Windows.Documents;13 using System.Windows.Input;14 using System.Windows.Media;15 using System.Windows.Media.Imaging;16 using System.Windows.Navigation;17 using System.Windows.Shapes;18 19 namespace wenjianduqu20 {21 /// <summary>22 /// MainWindow.xaml 的互動邏輯23 /// </summary>24 public partial class MainWindow : Window25 {26 public MainWindow()27 {28 InitializeComponent();29 }30 31 private void btnImport_Click(object sender, RoutedEventArgs e)32 {33 OpenFileDialog ofg = new OpenFileDialog();34 ofg.Filter = "文字檔|*.txt";
//如果沒選擇任何檔案,則返回35 if (ofg.ShowDialog()!=true)36 {37 return;38 }39 string filename = ofg.FileName;
//返回的是一個數組,所以要用IEnumerable介面40 IEnumerable<string> lines = File.ReadLines(filename,Encoding.Default);
//需要考慮資料讀取和寫入的編碼問題,所以要用Encoding.Default,要不然會出亂碼41 foreach (string line in lines)42 {43 string[]segs=line.Split(‘|‘);44 string name=segs[0];45 string age=segs[1];46 SqlHelper.ExecuteNonQuery("insert into T_Customer (Name,Age)
values(@Name,@Age)",47 new SqlParameter("@Name", name), new SqlParameter("@Age",
Convert.ToInt32(age)));48 }49 MessageBox.Show("匯入成功!成功匯入"+lines.Count()+"條資料");50 } 51 }52 }
自學.net(2)資料的匯入和匯出