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

C# 檔案操作常用範例:複製、建立、附加與編碼控制

     編輯:關於C語言

1. 將目前執行檔複製到啟動資料夾


string aimPath = @"C:\Documents and Settings\Administrator\「開始」選單\程式\啟動\Shut_Explorer.exe";
string srcPath = Process.GetCurrentProcess().MainModule.FileName; // 動態取得自身路徑

if (!File.Exists(aimPath))
    File.Copy(srcPath, aimPath);

2. 建立文字檔(覆寫模式)


string path = @"C:\Documents and Settings\Administrator\桌面\aa.txt";
if (!File.Exists(path))
{
    using (var sw = File.CreateText(path)) // 預設 UTF-8
    {
        sw.Write("開始了");
    }
}

3. 附加文字到現有檔案


using (var sw = File.AppendText(path))
{
    sw.WriteLine(boardId + "已完成");
}

4. 指定編碼建立/寫入檔案


using (var sw = new StreamWriter(path, false, Encoding.UTF8)) // false = 覆寫
{
    sw.Write("ererere");
}
  • StreamWriter 建構子:(path, append, encoding)。
  • 常用編碼:Encoding.UTF8、Encoding.GetEncoding("gb2312")、Encoding.Unicode(UTF-16)。

關鍵類別與命名空間

  • System.IO.File:靜態方法 Exists、Copy、CreateText、AppendText。
  • System.IO.StreamWriter:文字寫入器,支援編碼指定。
  • System.Diagnostics.Process:取得目前執行檔路徑。

最佳實務提醒

  1. 路徑含空白或特殊字元時,使用 @ 字串常值或 Path.Combine 組合。
  2. 所有 StreamWriter 操作建議包裹在 using 區塊,確保釋放檔案鎖定。
  3. 大量寫入時考慮 BufferedStream 或非同步 WriteAsync。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved