如果文件已经以Windows方式存在,则自动重命名该文件

SKJ*_*SKJ 54 .net c#

我的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)

  • 文件扩展名出错了,ex**C:\ file.txt**将成为**C:\ file.txt(1)**"等. (8认同)
  • @flindeberg好抓.我相信我已经纠正了这个错误. (4认同)
  • 供将来参考.需要注意的一点:如果正在检查的文件被命名为`some name(1)some text.txt`并且文件已经存在,如果要求保留这两个文件,Windows将重命名文件`some name (2)更多text.txt`而不是`some name(1)更多文本(1).txt`作为上面的代码而不是. (4认同)
  • 因此,.NET不内置此功能吗? (2认同)

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)