首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 檔案逐行讀寫與檔案/資料夾對話框完整指南

     編輯:關於C語言

逐行讀取文字檔

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");

開啟檔案對話框 (OpenFileDialog)

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;
}

選取資料夾對話框 (FolderBrowserDialog)

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。
  • Web 專案中檔案路徑請用 Server.MapPath 轉換虛擬路徑。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved