یک تابع بازگشتی باید بنویسی که وظیفه اش ایجاد نام منحصر به فرد برای فایل هست:
private string UniqueFileName(string path, char separateCharacter)
{
List<string> allPartOfSplitFileName = System.IO.Path.GetFileNameWithoutExtension(path).S plit(separateCharacter).ToList();
string lastPartOfFileName = allPartOfSplitFileName.LastOrDefault();
if (!string.IsNullOrEmpty(lastPartOfFileName))
{
int number = -1;
bool LastPartOfFileNameIsNumber;
try
{
number = int.Parse(lastPartOfFileName);
LastPartOfFileNameIsNumber = true;
}
catch
{
LastPartOfFileNameIsNumber = false;
}
path = System.IO.Path.GetDirectoryName(path) + "\\";
if (LastPartOfFileNameIsNumber)
{
number++;
allPartOfSplitFileName.Take(allPartOfSplitFileName .Count - 1).ToList().ForEach(part => path += part + "_");
}
else
{
number = 1;
allPartOfSplitFileName.ForEach(part => path += part + "_");
}
path += number + ".txt";
}
else
{
path = System.IO.Path.GetDirectoryName(path) + "\\"
+ System.IO.Path.GetFileNameWithoutExtension(path)
+ "1" + ".txt";
}
if (System.IO.File.Exists(path))
{
return UniqueFileName(path, separateCharacter);
}
return path;
}
برای ذخیره باید چک کنید اگر نام تکراری بود تابع را فراخوانی کنید(دکمه ذخیره):
private void button13_Click_1(object sender, EventArgs e)
{
string fileName = textBox1.Text;
string path = "Saved_Reports\\" + fileName + ".txt";
if (File.Exists(path))
{
path = UniqueFileName(path, '_');
}
stiReport1.SaveDocument(path);
}
'_' کاراکتری هست که نام و عدد را از هم جدا میکند.