我的C#代码根据输入生成多个文本文件并将其保存在文件夹中.另外,我假设文本文件的名称将是相同的输入.(输入只包含字母)如果两个文件具有相同的名称则简单地覆盖以前的文件.但我想保留这两个文件.
我不想将当前日期时间或随机数附加到第二个文件名.相反,我希望以与Windows相同的方式执行此操作.如果最前一页文件名是AAA.txt,然后第二个文件名是AAA(2).txt文件,第三文件名将是AAA(3)的.txt .....第N文件名将是AAA(N)的.txt .
string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray();
foreach (var item in allFiles)
{
//newFileName is the txt file which is going to be saved in the provided folder
if (newFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase))
{
// What to do here ?
}
}
Run Code Online (Sandbox Code Playgroud)
cad*_*ll0 122
这将检查是否存在具有tempFileName的文件,并将该数字递增1,直到找到目录中不存在的名称.
int count = 1;
string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
string extension = Path.GetExtension(fullPath);
string path = Path.GetDirectoryName(fullPath);
string newFullPath = fullPath;
while(File.Exists(newFullPath))
{
string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
newFullPath = Path.Combine(path, tempFileName + extension);
}
Run Code Online (Sandbox Code Playgroud)
Jae*_*aex 19
使用此代码,如果filename是"Test(3).txt",那么它将变为"Test(4).txt".
public static string GetUniqueFilePath(string filePath)
{
if (File.Exists(filePath))
{
string folderPath = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileNameWithoutExtension(filePath);
string fileExtension = Path.GetExtension(filePath);
int number = 1;
Match regex = Regex.Match(fileName, @"^(.+) \((\d+)\)$");
if (regex.Success)
{
fileName = regex.Groups[1].Value;
number = int.Parse(regex.Groups[2].Value);
}
do
{
number++;
string newFileName = $"{fileName} ({number}){fileExtension}";
filePath = Path.Combine(folderPath, newFileName);
}
while (File.Exists(filePath));
}
return filePath;
}
Run Code Online (Sandbox Code Playgroud)
小智 8
其他示例不考虑文件名/扩展名.
干得好:
public static string GetUniqueFilename(string fullPath)
{
if (!Path.IsPathRooted(fullPath))
fullPath = Path.GetFullPath(fullPath);
if (File.Exists(fullPath))
{
String filename = Path.GetFileName(fullPath);
String path = fullPath.Substring(0, fullPath.Length - filename.Length);
String filenameWOExt = Path.GetFileNameWithoutExtension(fullPath);
String ext = Path.GetExtension(fullPath);
int n = 1;
do
{
fullPath = Path.Combine(path, String.Format("{0} ({1}){2}", filenameWOExt, (n++), ext));
}
while (File.Exists(fullPath));
}
return fullPath;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
71542 次 |
最近记录: |