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

时间:2012-10-24 12:59:31

标签: c# .net

我的C#代码根据输入生成多个文本文件并将其保存在文件夹中。另外,我假设文本文件的名称与输入相同。(输入只包含字母) 如果两个文件具有相同的名称,则它只是覆盖以前的文件。 但我想保留这两个文件。

我不想将当前日期时间或随机数附加到第二个文件名。相反,我希望以与Windows相同的方式执行此操作。如果fisrt文件名是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 ?                
            }
        }

10 个答案:

答案 0 :(得分:120)

这将检查是否存在具有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);
}

答案 1 :(得分:19)

使用此代码,如果filename是" Test(3).txt"然后它将成为"测试(4).txt"。

public static string GetUniqueFilePath(string filepath)
{
    if (File.Exists(filepath))
    {
        string folder = Path.GetDirectoryName(filepath);
        string filename = Path.GetFileNameWithoutExtension(filepath);
        string extension = Path.GetExtension(filepath);
        int number = 1;

        Match regex = Regex.Match(filepath, @"(.+) \((\d+)\)\.\w+");

        if (regex.Success)
        {
            filename = regex.Groups[1].Value;
            number = int.Parse(regex.Groups[2].Value);
        }

        do
        {
            number++;
            filepath = Path.Combine(folder, string.Format("{0} ({1}){2}", filename, number, extension));
        }
        while (File.Exists(filepath));
    }

    return filepath;
}

答案 2 :(得分:7)

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

你走了:

    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;
    }

答案 3 :(得分: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++);
  }
}

如果原始文件名不存在,则会使用原始文件名,如果不是,则使用括号中的索引获取新文件名(尽管此代码不考虑扩展名) )。如果新生成的名称"文本(001)"然后它会被使用,直到找到有效的未使用文件名为止。

答案 4 :(得分: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);
    }

答案 5 :(得分: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;
    }

答案 6 :(得分:0)

您可以声明Dictionary<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)...

答案 7 :(得分: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";

答案 8 :(得分:0)

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++;
}

答案 9 :(得分:0)

关于Giuseppe关于Windows重命名文件的方式的评论我在一个版本上找到了任何现有索引,即文件名中的(2),并根据窗口相应地重命名文件。假设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);
    }
相关问题