60

我的 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 ?                
            }
        }
4

10 回答 10

141

这将检查带有 tempFileName 的文件是否存在,并将数字加一,直到找到目录中不存在的名称。

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);
}
于 2012-10-24T13:09:10.490 回答
22

使用此代码,如果文件名是“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;
}
于 2014-03-13T09:00:10.397 回答
9

其他示例不考虑文件名/扩展名。

干得好:

    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;
    }
于 2012-10-24T13:16:24.660 回答
1

怎么样:

int count = 1;
String tempFileName = newFileName;

foreach (var item in allFiles)
{
  if (tempFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase))
  {
    tempFileName = String.Format("{0}({1})", newFileName, count++);
  }
}

如果它不存在,这将使用原始文件名,如果不存在,它将采用带有括号中索引的新文件名(尽管此代码没有考虑扩展名)。如果使用新生成的名称“text(001)”,那么它将递增,直到找到有效的未使用文件名。

于 2012-10-24T13:03:32.590 回答
1
int count= 0;

文件是文件名

while (File.Exists(fullpathwithfilename))  //this will check for existence of file
{ 
// below line names new file from file.xls to file1.xls   
fullpathwithfilename= fullpathwithfilename.Replace("file.xls", "file"+count+".xls"); 

count++;
}
于 2013-09-27T09:26:48.657 回答
1
public static string AutoRenameFilename(FileInfo file)
    {
        var filename = file.Name.Replace(file.Extension, string.Empty);
        var dir = file.Directory.FullName;
        var ext = file.Extension;

        if (file.Exists)
        {
            int count = 0;
            string added;

            do
            {
                count++;
                added = "(" + count + ")";
            } while (File.Exists(dir + "\\" + filename + " " + added + ext));

            filename += " " + added;
        }

        return (dir + filename + ext);
    }
于 2014-06-05T01:31:56.553 回答
1

关于 Giuseppe 对 windows 重命名文件方式的评论,我在一个版本上工作,该版本在文件名中找到任何现有索引,即 (2),并根据 windows 相应地重命名文件。假定 sourceFileName 有效,并且此时假定用户对目标文件夹具有写权限:

using System.IO;
using System.Text.RegularExpressions;

    private void RenameDiskFileToMSUnique(string sourceFileName)
    {
        string destFileName = "";
        long n = 1;
        // ensure the full path is qualified
        if (!Path.IsPathRooted(sourceFileName)) { sourceFileName = Path.GetFullPath(sourceFileName); }

        string filepath = Path.GetDirectoryName(sourceFileName);
        string fileNameWOExt = Path.GetFileNameWithoutExtension(sourceFileName);
        string fileNameSuffix = "";
        string fileNameExt = Path.GetExtension(sourceFileName);
        // if the name includes the text "(0-9)" then we have a filename, instance number and suffix  
        Regex r = new Regex(@"\(\d+\)");
        Match match = r.Match(fileNameWOExt);
        if (match.Success) // the pattern (0-9) was found
        {
            // text after the match
            if (fileNameWOExt.Length > match.Index + match.Length) // remove the format and create the suffix
            {
                fileNameSuffix = fileNameWOExt.Substring(match.Index + match.Length, fileNameWOExt.Length - (match.Index + match.Length));
                fileNameWOExt = fileNameWOExt.Substring(0, match.Index);
            }
            else // remove the format at the end
            {
                fileNameWOExt = fileNameWOExt.Substring(0, fileNameWOExt.Length - match.Length);
            }
            // increment the numeric in the name
            n = Convert.ToInt64(match.Value.Substring(1, match.Length - 2)) + 1;
        }
        // format variation: indexed text retains the original layout, new suffixed text inserts a space!
        do
        {
            if (match.Success) // the text was already indexed
            {
                if (fileNameSuffix.Length > 0)
                {
                    destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}{3}", fileNameWOExt, (n++), fileNameSuffix, fileNameExt));
                }
                else
                {
                    destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}", fileNameWOExt, (n++), fileNameExt));
                }
            }
            else // we are adding a new index
            {
                destFileName = Path.Combine(filepath, String.Format("{0} ({1}){2}", fileNameWOExt, (n++), fileNameExt));
            }
        }
        while (File.Exists(destFileName));

        File.Copy(sourceFileName, destFileName);
    }
于 2017-11-26T16:26:47.490 回答
1

我正在寻找一种可以移动文件的解决方案,并确保目标文件名是否尚未被使用。它将遵循与 Windows 相同的逻辑,并在重复文件后附加一个数字,并带有括号。

感谢@cadrell0,最佳答案帮助我找到了以下解决方案:

    /// <summary>
    /// Generates full file path for a file that is to be moved to a destinationFolderDir. 
    /// 
    /// This method takes into account the possiblity of the file already existing, 
    /// and will append number surrounded with brackets to the file name.
    /// 
    /// E.g. if D:\DestinationDir contains file name file.txt,
    /// and your fileToMoveFullPath is D:\Source\file.txt, the generated path will be D:\DestinationDir\file(1).txt
    /// 
    /// </summary>
    /// <param name="destinationFolderDir">E.g. D:\DestinationDir </param>
    /// <param name="fileToMoveFullPath">D:\Source\file.txt</param>
    /// <returns></returns>
    public string GetFullFilePathWithDuplicatesTakenInMind(string destinationFolderDir, string fileToMoveFullPath)
    {
        string destinationPathWithDuplicatesTakenInMind;

        string fileNameWithExtension = Path.GetFileName(fileToMoveFullPath);
        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileToMoveFullPath);
        string fileNameExtension = Path.GetExtension(fileToMoveFullPath);

        destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, fileNameWithExtension);

        int count = 0;
        while (File.Exists(destinationPathWithDuplicatesTakenInMind))
        {
            destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, $"{fileNameWithoutExtension}({count}){fileNameExtension}");
            count = count + 1; // sorry, not a fan of the ++ operator.
        }

        return destinationPathWithDuplicatesTakenInMind;
    }
于 2017-09-20T15:37:03.113 回答
0

现在工作正常。谢谢大家的回答。。

string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray();
        string tempFileName = fileName;
        int count = 1;
        while (allFiles.Contains(tempFileName ))
        {
            tempFileName = String.Format("{0} ({1})", fileName, count++); 
        }

        output = Path.Combine(folderPath, tempFileName );
        string fullPath=output + ".xml";
于 2012-10-24T14:40:42.257 回答
0

您可以声明 aDictionary<string,int>来保存每个根文件名的保存次数。之后,在您的Save方法上,只需增加计数器并将其附加到基本文件名:

var key = fileName.ToLower();
string newFileName;
if(!_dictionary.ContainsKey(key))
{
    newFileName = fileName;
    _dictionary.Add(key,0);
}
else
{
    _dictionary[key]++;
   newFileName = String.Format("{0}({1})", fileName, _dictionary[key])
}

这样,每个不同的文件名都有一个计数器:AAA(1), AAA(2); BBB(1)...

于 2012-10-24T13:17:03.053 回答