[英]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_initial
和filename_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.