简体   繁体   English

如果文件已经存在于c#中,则增加文件名

[英]Increment the file name if the file already exists in c#

Tried the below logic in windows form for file name incremental, if the file already exists in the specified path. 如果文件已存在于指定的路径中,请尝试在Windows窗体中尝试以下逻辑以使文件名递增。 but the files are created with the names "New1.txt2","New1.txt2.txt3". 但是创建的文件名为“ New1.txt2”,“ New1.txt2.txt3”。 how the files can be created as "New1.txt", "New2.txt", "New3.txt"...."Newn.txt" on every button Click? 如何在每个按钮上将文件创建为“ New1.txt”,“ New2.txt”,“ New3.txt” ......“ Newn.txt”?

String filename =@"C:\path";
if (File.Exists(filename))
        {
            count++;
            filename = filename + count.ToString()+".txt";

There is one more problem in your code. 您的代码中还有另外一个问题。 Why do you have file names like "New1.txt2","New1.txt2.txt3", "New1.txt2.txt3.txt4"? 为什么会有诸如“ New1.txt2”,“ New1.txt2.txt3”,“ New1.txt2.txt3.txt4”之类的文件名? Because you don't keep initial filename somewhere. 因为您不将初始文件名保存在某个地方。 So, I'd propose to keep two variables for filenames: for instance, filename_initial and filename_current . 因此,我建议为文件名保留两个变量:例如, filename_initialfilename_current

Try something like this: 尝试这样的事情:

String filename_initial = @"C:\path\New.txt";
String filename_current = filename_initial;
count = 0;
while (File.Exists(filename_current))
{
    count++;
    filename_current = Path.GetDirectoryName(filename_initial)
                     + Path.DirectorySeparatorChar
                     + Path.GetFileNameWithoutExtension(filename_initial)
                     + count.ToString()
                     + Path.GetExtension(filename_initial);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# 当文件名已经存在时增加文件名的问题 - C# Problem incrementing a file name when the file name already exists 查询以验证C#中是否已存在文件 - Query to validate if a file already exists in C# C#移动文件并重命名(如果已经存在) - C# move file and rename it, if it already exists IOException文件已存在C# - IOException file already exists C# 如果 C# 中的文件夹中存在文件名更改 - File name change if exists in a folder in C# C# Google Storage Client - 上传文件 - 如果已经存在则失败 - C# Google Storage Client - Upload file - Fail if already exists “数据库已经存在。 选择一个不同的数据库名称。 恢复C#Win App数据库后,无法附加文件…”错误 - “Database already exists. Choose a different database name. Cannot attach the file…” error after restoring database of c# win app 无法将文件添加到解决方案:“名称为[name]的文件或文件夹已存在” - Cannot add file to solution: “A file or folder with the name [name] already exists” C# 如果文件已经存在,自动用当前日期和时间重命名文件 - C# Automatically Rename a File with the Current Date and Time if the File Already Exists 如果文件在 C# 中的相同位置已存在,则始终创建新文件 - always create new file if file already exists with same location in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM