2018/10/17

[C#] WPF Read Text File

WPF 如何讀取文字檔

準備一個file.txt檔案,內容為
  1. 123
  2. 456
  3. 789
假設檔案放在C槽,宣告路徑為
  1. private string filePath = "C:\\";

判斷檔案是否存在
  1. if (!File.Exists(@filePath + "file.txt"))
  2. {
  3. MessageBox.Show("The file.txt file does not exist!");
  4. }
變數的值就可以透過TextReader讀取文字檔的內容來設定
(以下寫法為逐行讀取內容來設定整數a=123, b=456, c=789)
  1. private int a, b, c;
  2. private string filePath = "C:\\";
  3. private TextReader file_tr;
  4.  
  5. public MainWindow()
  6. {
  7. file_tr = File.OpenText(@filePath + "file.txt");
  8. a = Int32.Parse(file_tr.ReadLine());
  9. b = Int32.Parse(file_tr.ReadLine());
  10. c = Int32.Parse(file_tr.ReadLine());
  11. file_tr.Close();
  12. }
透過轉型把讀取的內容字串轉成需要的型態,例如以下方法:
  1. int a = Int32.Parse(file_tr.ReadLine());
  2. double b = double.Parse(file_tr.ReadLine());
  3. string str = file_tr.ReadLine()

沒有留言:

張貼留言