代碼:
string path = Application.StartupPath; // 取得目錄
FileStream so = new FileStream(path, FileMode.Create); // 錯誤:path 是目錄
錯誤:對路徑 "F:\...\Debug" 的存取被拒絕
FileStream 需要**檔案路徑**,不能是目錄。對目錄開啟 FileMode.Create 會嘗試建立同名檔案,但目錄已存在同名導致存取拒絕。
string filePath = Path.Combine(Application.StartupPath, "data.txt"); // 或 xxx.log
FileStream so = new FileStream(filePath, FileMode.Create);
Path.Combine 自動處理路徑分隔符,跨平台安全。FileMode.Create:建立新檔或覆蓋舊檔;FileMode.Append 續寫。so.Dispose() 或 using 區塊。「目錄 ≠ 檔案」是 IO 程式設計的基本常識。