.NET System::IO::Path 類別提供靜態方法,幾行代碼即可安全建立、使用、清理暫存檔,避免手工拼湊路徑與檔名衝突。
using namespace System::Security;
using namespace System::IO;
String^ tempFolder;
try {
tempFolder = Path::GetTempPath(); // 可能拋出 SecurityException
} catch (SecurityException^ ex) {
// 權限不足
} catch (Exception^ ex) {
// 其他錯誤
}
String^ fileName = String::Empty;
try {
fileName = Path::GetTempFileName(); // 建立 0 位元組檔並回傳完整路徑
FileInfo^ fi = gcnew FileInfo(fileName);
fi->Attributes = FileAttributes::Temporary; // 設為暫存屬性,運行期快取優化
// 使用檔案...
} catch (Exception^ ex) {
// 錯誤處理
}
GetTempFileName 保證檔名唯一;Temporary 屬性提示檔案系統儘量保留在快取,減少 I/O。
// 寫入
StreamWriter^ sw = File::AppendText(fileName);
sw->WriteLine("A test sample data");
sw->Flush(); sw->Close();
// 讀取(一次讀完)
StreamReader^ sr = File::OpenText(fileName);
String^ content = sr->ReadToEnd();
sr->Close();
File::Delete(fileName); // 簡單直接
建議在 finally 區塊或 using 模式(C++/CLI 支援 IDisposable 模式)確保清理。
String^ tempFile = nullptr;
try {
tempFile = Path::GetTempFileName();
FileInfo^ fi = gcnew FileInfo(tempFile);
fi->Attributes = FileAttributes::Temporary;
StreamWriter^ sw = File::AppendText(tempFile);
sw->WriteLine("Log entry at " + DateTime::Now);
sw->Close();
// 處理檔案...
}
finally {
if (tempFile != nullptr && File::Exists(tempFile))
File::Delete(tempFile);
}