如果它已经存在于Windows操作方式,自动重命名文件 [英] Automatically rename a file if it already exists in Windows way

查看:204
本文介绍了如果它已经存在于Windows操作方式,自动重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C#code为生成多个文本文件的基础上的输入和保存的一个文件夹中。另外,我假设文本文件的名称将与输入相同。(输入只包含字母) 如果两个文件具有相同的名字,那么它仅仅是覆盖previous文件。 不过,我想保留这两个文件。

我不想附加当前的日期时间或一个随机数到第二文件名。相反,我想这样做同样的方式Windows一样。如果最前一页文件名为aaa.txt到本地,然后第二个文件名是AAA(2).TXT,第三个文件的名字将是AAA(3).TXT .....第N个文件名是AAA(N).TXT

 的String [] allFiles = Directory.GetFiles(FOLDERPATH)。选择(文件名=> Path.GetFileNameWithoutExtension(文件名))。的ToArray();
        的foreach(在allFiles VAR项)
        {
            // newFileName是TXT文件,该文件将被保存在文件夹提供
            如果(newFileName.Equals(项目,StringComparison.InvariantCultureIgnoreCase))
            {
                //这里做什么?
            }
        }
 

解决方案

这将检查文件与tempFileName存在并且由一个递增数,直到它找到一个不存在目录中的名称。

 诠释计数= 1;

字符串fileNameOnly = Path.GetFileNameWithoutExtension(FULLPATH);
串延长= Path.GetExtension(FULLPATH);
字符串路径= Path.GetDirectoryName(FULLPATH);
字符串newFullPath = FULLPATH;

而(File.Exists(newFullPath))
{
    字符串tempFileName =的String.Format({0}({1}),fileNameOnly,算上++);
    newFullPath = Path.Combine(路径,tempFileName +扩展名);
}
 

My C# code is generating several text files based on input and saving those in a folder. Also, I am assuming that the name of the text file will be same as input.(The input contains only letters) If two files has same name then it is simply overwriting the previous file. But I want to keep both files.

I don't want to append current date time or a random number to the 2nd file name. Instead I want to do it the same way Windows does. If the fisrt file name is AAA.txt , then second file name is AAA(2).txt, third file name will be AAA(3).txt.....N th file name will be 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 ?                
            }
        }

解决方案

This will check for the existence of files with tempFileName and increment the number by one until it finds a name that does not exist in the directory.

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

这篇关于如果它已经存在于Windows操作方式,自动重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆