核心代碼
using System.IO;
foreach (string line in File.ReadAllLines(@"C:\HistoryID.txt")) {
comboBox1.Items.Add(line.Trim());
}
進階:異步讀取避免 UI 凍結
private async void Form_Load(object sender, EventArgs e) {
try {
string[] lines = await Task.Run(() => File.ReadAllLines(@"C:\HistoryID.txt"));
comboBox1.BeginUpdate();
comboBox1.Items.AddRange(lines.Select(l => l.Trim()).ToArray());
comboBox1.EndUpdate();
} catch (Exception ex) {
MessageBox.Show("讀取歷史失敗: " + ex.Message);
}
}
持久化建議
- 文件路徑用
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) 避免權限問題。
- 登錄成功後
File.AppendAllLines(path, new[]{username}),去重可用 HashSet。
- 考慮用
Settings.Default (應用程序設置) 存儲 StringCollection,自動序列化到 user.config,無需手動文件操作。