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

托管 C++ 利用 Path 類別處理暫存檔案

     編輯:關於C++

.NET System::IO::Path 類別提供靜態方法,幾行代碼即可安全建立、使用、清理暫存檔,避免手工拼湊路徑與檔名衝突。

1. 取得暫存目錄

using namespace System::Security;
using namespace System::IO;

String^ tempFolder;
try {
    tempFolder = Path::GetTempPath(); // 可能拋出 SecurityException
} catch (SecurityException^ ex) {
    // 權限不足
} catch (Exception^ ex) {
    // 其他錯誤
}

2. 建立唯一暫存檔並優化效能

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。

3. 寫入與讀取資料

// 寫入
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();

4. 刪除暫存檔

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);
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved