Skip to main content
 首页 » 编程设计

c#之一种优雅的重命名文件的方法,如果它在归档时已经存在

2024年02月23日16zhoujg

我想编写一个归档函数,将文件夹中的所有文件移动到使用当前日期的归档子文件夹中。该过程可能在一天内运行多次,因此需要处理重复项。

归档规则如下:

  1. 如果文件名已经存在,我想添加下划线“_”和 一个数字(从 1 开始)。
  2. 如果文件名已经被修改了我想 增加数字。

我可以使用大量 File.Exist 和 LastIndexOf 调用来做到这一点,但是有没有更优雅的方法?也许用 LINQ?

编辑:

这是我已有的代码。它有点粗糙和准备就绪,但它给出了我想要做什么的想法。

/// <summary> 
/// Move the local file into the archive location. 
/// If the file already exists then add a counter to the file name or increment the existing counter 
/// </summary> 
/// <param name="LocalFilePath">The full path of the file to be archived</param> 
/// <param name="ArchiveFilePath">The proposed full path of the file once it's been archived</param> 
private void ArchiveFile(string LocalFilePath, string ArchiveFilePath) 
{ 
    // Ensure the file name doesn't already exists in the location we want to move it to 
    if (File.Exists(ArchiveFilePath) == true) 
    { 
        // Does the archive file have a number at the end? 
        string[] archiveSplit = Path.GetFileNameWithoutExtension(ArchiveFilePath).Split('_'); 
        if( archiveSplit.Length == 1) 
        { 
            // No number detected so append the number 1 to the filename 
            string newArcFileName = string.Format("{0}_1.{1}", 
                Path.GetFileNameWithoutExtension(ArchiveFilePath), Path.GetExtension(ArchiveFilePath)); 
 
            // Create the new full path 
            string newArcPath = Path.Combine(Path.GetDirectoryName(ArchiveFilePath), newArcFileName); 
 
            // recursively call the archive folder to ensure the new file name doesn't exist before moving 
            ArchiveFile( LocalFilePath, newArcPath); 
        } 
        else 
        { 
            // Get the number of the last element of the split 
            int lastNum = Convert.ToInt32( archiveSplit.Last().Substring(1) ) +1; 
 
            // Rebuild the filename using the incremented number 
            string newArcFileName = archiveSplit[0]; 
            for (int i = 1; i < archiveSplit.Length; i++) 
            { 
                newArcFileName += archiveSplit[i]; 
            } 
            // finally add the number and extension 
            newArcFileName = string.Format("{0}_{1}.{2}", newArcFileName, lastNum, Path.GetExtension(ArchiveFilePath)); 
 
            // Create the new full path 
            string newArcPath = Path.Combine(Path.GetDirectoryName(ArchiveFilePath), newArcFileName); 
 
            // recursively call the archive folder to ensure the new file name doesn't exist before moving 
            ArchiveFile(LocalFilePath, newArcPath); 
        } 
    } 
    else 
    { 
        // There is no file with a matching name 
        File.Move(LocalFilePath, ArchiveFilePath); 
    } 
} 

请您参考如下方法:

Directory 类有一个方法来接收其中所有文件的列表。该方法允许您指定过滤字符串,如下所示:

Directory.GetFiles(directoryPath, filterString); 

如果您已经知道文件名前缀,则可以使用该过滤器字符串来获取该模式内的所有文件:

filterString = string.Format("{0}_*.{1}", defaultFileNameWithoutExtension, defaultExtension); 

然后您可以简单地选择后缀最高的那个,提取后缀数字,增加它并构建新的(未使用的)文件名。

免责声明:这是用心写的,如有错误,请随时编辑:)