3

Tried the below logic in windows form for file name incremental, if the file already exists in the specified path. but the files are created with the names "New1.txt2","New1.txt2.txt3". how the files can be created as "New1.txt", "New2.txt", "New3.txt"...."Newn.txt" on every button Click?

String filename =@"C:\path";
if (File.Exists(filename))
        {
            count++;
            filename = filename + count.ToString()+".txt";
Newbee
  • 55
  • 1
  • 5
  • 2
    Possible duplicate of [Automatically rename a file if it already exists in Windows way](https://stackoverflow.com/questions/13049732/automatically-rename-a-file-if-it-already-exists-in-windows-way) – Ňɏssa Pøngjǣrdenlarp Nov 23 '18 at 02:36
  • 1
    you can use Path.GetFileNameWithoutExtension to get file name without extension and then use increment logic – Anu Viswan Nov 23 '18 at 02:36
  • Consider using a timestamp, like 2018112416350001, including the milliseconds. You get the same benefit of being able to identify the sequence, but the name of your file doesn't have to depend on which files already exist. – Scott Hannen Nov 23 '18 at 02:44
  • 1
    Also, consider what happens if two threads run the same code and come up with the same filename as a result (race condition). – mjwills Nov 23 '18 at 03:15

1 Answers1

5

There is one more problem in your code. Why do you have file names like "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.

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);
}
Ilya
  • 4,583
  • 4
  • 26
  • 51
  • Thankyou for the response, for the above statement, the files created with the name "New12", "New123" – Newbee Nov 23 '18 at 02:48
  • You are welcome. Also I'd replace `if` by `while`, please look at the second part of my answer. – Ilya Nov 23 '18 at 02:51
  • using the second part the files were not generated – Newbee Nov 23 '18 at 03:09
  • Why? After this `while` loop you have the name of non-existent file in the `filename_current`. Do you use this filename for creation of files? Try to use a debugger to catch the problem. – Ilya Nov 23 '18 at 03:18
  • It worked!! with the second part .the files are perfectly getting generated as new1, new2, new3.... i made little modification in my path. Thanks much!! – Newbee Nov 23 '18 at 03:20