এই প্রশ্নের ইতিমধ্যে উত্তর দেওয়া হয়েছে, তবে এখানে একটি আসল ওয়ার্ল্ড সলিউশন যা ডিরেক্টরিটি উপস্থিত রয়েছে কিনা তা পরীক্ষা করে এবং পাঠ্য ফাইলটি উপস্থিত থাকলে শেষ পর্যন্ত একটি সংখ্যা যুক্ত করে। আমি এটি লিখেছিলাম এমন একটি উইন্ডোজ পরিষেবাতে প্রতিদিনের লগ ফাইলগুলি তৈরি করতে ব্যবহার করি। আমি আশা করি এটা কারো সাহায্যে লাগবে.
// How to create a log file with a sortable date and add numbering to it if it already exists.
public void CreateLogFile()
{
// filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
var filePath = "C:\\Logs";
// Append a backslash if one is not present at the end of the file path.
if (!filePath.EndsWith("\\"))
{
filePath += "\\";
}
// Create the path if it doesn't exist.
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// Create the file name with a calendar sortable date on the end.
var now = DateTime.Now;
filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);
// Check if the file that is about to be created already exists. If so, append a number to the end.
if (File.Exists(filePath))
{
var counter = 1;
filePath = filePath.Replace(".txt", " (" + counter + ").txt");
while (File.Exists(filePath))
{
filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
counter++;
}
}
// Note that after the file is created, the file stream is still open. It needs to be closed
// once it is created if other methods need to access it.
using (var file = File.Create(filePath))
{
file.Close();
}
}