導出 Excel 文件命名格式:`MMDD_序號` (如 `0218_01`),同一文件夾下同一天序號遞增。
public string GetNextExportFileName(string folderPath) {
string prefix = DateTime.Now.ToString("MMdd") + "_"; // 如 "0218_"
int maxSeq = 0;
if (Directory.Exists(folderPath)) {
string[] files = Directory.GetFiles(folderPath);
foreach (string file in files) {
string fileName = Path.GetFileNameWithoutExtension(file); // 不含擴展名
if (fileName.StartsWith(prefix)) {
string seqPart = fileName.Substring(prefix.Length); // 取 "_xx" 後部分
if (int.TryParse(seqPart, out int seq)) {
maxSeq = Math.Max(maxSeq, seq);
}
}
}
}
int nextSeq = maxSeq + 1;
return $"{prefix}{nextSeq:D2}.xlsx"; // 如 "0218_03.xlsx"
}
public string CreateUniqueExportFile(string folderPath) {
string prefix = DateTime.Now.ToString("MMdd") + "_";
for (int seq = 1; seq <= 99; seq++) {
string fileName = $"{prefix}{seq:D2}.xlsx";
string fullPath = Path.Combine(folderPath, fileName);
try {
// 嘗試獨佔創建文件流,原子操作
using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) {
return fullPath; // 成功返回路徑,調用者寫入數據
}
} catch (IOException) {
// 文件已存在,嘗試下一序號
}
}
throw new InvalidOperationException("當日導出序號已用盡 (99)");
}
掃描文件夾解析序號簡單有效,併發場景必須採用**原子性文件創建** (`FileMode.CreateNew`) 保證唯一性,而非單純掃描+計算。