Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically rename a file if it already exists in Windows way

Tags:

c#

.net

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 ?                             }         } 
like image 939
skjcyber Avatar asked Oct 24 '12 12:10

skjcyber


People also ask

How do I automatically rename a file with the same name?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

Is it possible for you to rename a file that is open in another window?

Your premise is false. Files cannot be renamed if they are intentionally locked, a feature of many operating systems, including Linux and Windows, to prevent unpredictable results when trying to write to a file.

How do you rename a file that is in use?

To rename a file or folder:Right-click on the item and select Rename, or select the file and press F2 . Type the new name and press Enter or click Rename.


1 Answers

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); } 
like image 62
cadrell0 Avatar answered Oct 13 '22 16:10

cadrell0