int fileCount = 0;
if (File.Exists(textBox1.Text.Trim()))
{
using (StreamReader sr = new StreamReader(textBox1.Text.Trim()))
{
while (sr.Peek() > -1) // -1 表示串流結束
{
listBox1.Items.Add(sr.ReadLine());
fileCount++;
}
} // 自動呼叫 Close() 與 Dispose()
}
重點:using 區塊確保資源釋放;Peek() 不消耗字元;ReadLine() 移除換行符。
using (StreamWriter sw = new StreamWriter(@"D:\result.txt"))
{
for (int i = 0; i < 10; i++)
{
sw.WriteLine("這是第" + i + "行資料");
}
}
WriteLine 自動附加換行;using 確保緩衝區刷新並關閉檔案。
bool fileOk = File.Exists(filePath);
bool dirOk = Directory.Exists(@"D:\LatestVersion");
string resultFile = "";
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.InitialDirectory = @"D:\Patch";
dlg.Filter = "所有檔案 (*.*)|*.*|文字檔 (*.txt)|*.txt";
dlg.FilterIndex = 2; // 預設選「文字檔」
dlg.RestoreDirectory = true; // 關閉前還原當前目錄
if (dlg.ShowDialog() == DialogResult.OK)
resultFile = dlg.FileName;
}
string resultFolder = "";
using (FolderBrowserDialog dlg = new FolderBrowserDialog())
{
dlg.RootFolder = Environment.SpecialFolder.MyComputer;
dlg.Description = "請選擇目標資料夾";
if (dlg.ShowDialog() == DialogResult.OK)
resultFolder = dlg.SelectedPath;
}
| 操作 | 方法 | 備註 |
|---|---|---|
| 複製 | File.Copy(src, dest, overwrite) | overwrite=true 覆蓋既有檔 |
| 移動/重命名 | File.Move(src, dest) | 跨磁碟實際為複製+刪除 |
| 刪除 | File.Delete(path) | 檔不存在不拋例外 |
| 取得檔名 | Path.GetFileName(path) | 含副檔名 |
| 取得目錄 | Path.GetDirectoryName(path) | |
| 取得無副檔名檔名 | Path.GetFileNameWithoutExtension(path) | |
| 合併路徑 | Path.Combine(dir, file) | 自動處理分隔符 |
StreamReader/Writer、FileStream、對話框均實作 IDisposable,務必用 using。@ 逐字字串或 Path.Combine 避免跳脫字元錯誤。File.ReadAllLines/WriteAllLines 或非同步 ReadAllTextAsync。Server.MapPath 轉換虛擬路徑。