A way to get a unique file name if the specified file name already exists (.NET)

Is there a built-in .NET function to get a unique file name if the file name already exists? Therefore, if I try to save MyDoc.doc , and it already exists, the file will be saved with the name MyDoc(1).doc , just like downloading a browser.

If not, what is the effective way to achieve this result?

I am using the File.Move function at the time of btw.

+4
source share
4 answers

check the name on Regex *.\(\d+\) , if it does not match, add (1) if it matches the increase in the number in brackets.

+2
source

EDIT

Here is another solution I came up with after Steven Sudat's comment:

 static void Main(string[] args) { CopyFile(new FileInfo(@"D:\table.txt"), new FileInfo(@"D:\blah.txt")); } private static void CopyFile(FileInfo source, FileInfo destination) { int attempt = 0; FileInfo originalDestination = destination; while (destination.Exists || !TryCopyTo(source, destination)) { attempt++; destination = new FileInfo(originalDestination.FullName.Remove( originalDestination.FullName.Length - originalDestination.Extension.Length) + " (" + attempt + ")" + originalDestination.Extension); } } private static bool TryCopyTo(FileInfo source, FileInfo destination) { try { source.CopyTo(destination.FullName); return true; } catch { return false; } } 
+3
source

I don’t know, but creating it is not difficult:

 if filename does not exists then save file as filename else n = 1 while filename(n) exists: n += 1 save file as filename(n) 
+1
source

As the other answers show, there are several ways to do this, but one thing to be aware of is that if processes other than yours can create files, you have to be careful, because if you check that the file name available when you save a new file, some other process may already save the file using this name, and you will overwrite this file.

+1
source

Source: https://habr.com/ru/post/1313513/


All Articles