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 ? } }
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With