準備一個file.txt檔案,內容為
123 456 789假設檔案放在C槽,宣告路徑為
private string filePath = "C:\\";
判斷檔案是否存在
if (!File.Exists(@filePath + "file.txt"))
{
MessageBox.Show("The file.txt file does not exist!");
}
變數的值就可以透過TextReader讀取文字檔的內容來設定(以下寫法為逐行讀取內容來設定整數a=123, b=456, c=789)
private int a, b, c;
private string filePath = "C:\\";
private TextReader file_tr;
public MainWindow()
{
file_tr = File.OpenText(@filePath + "file.txt");
a = Int32.Parse(file_tr.ReadLine());
b = Int32.Parse(file_tr.ReadLine());
c = Int32.Parse(file_tr.ReadLine());
file_tr.Close();
}
透過轉型把讀取的內容字串轉成需要的型態,例如以下方法: int a = Int32.Parse(file_tr.ReadLine()); double b = double.Parse(file_tr.ReadLine()); string str = file_tr.ReadLine()
沒有留言:
張貼留言