Automatically rename a file if it already exists in Windows way
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);
}
C# move file and rename it, if it already exists
well you can handle all the possible errors that can be thrown if you want to be certain.
try
{
File.Move(oldPath, newPath);
}
catch (ArgumentNullException)
{
//source of dest filename is null
}
catch(ArgumentException)
{
//source or dest file name/path not valid
}
catch(UnauthorizedAccessException)
{
//no permission
}
catch (DirectoryNotFoundException)
{
//dir not found
}
catch(PathTooLongException)
{
//path too long
}
catch(NotSupportedException)
{
//source or desk name is invalid format
}
catch (IOException)
{
if (File.Exists(newPath))
//file exists
else if (!File.Exists(oldPath))
//old path does not exist
else
//Unknown error
}
you can find all the possible ones on MSDN
If File Already Exists Rename it
I'd go with File.Move
to rename a file:
https://msdn.microsoft.com/en-us/library/system.io.file.move%28v=vs.110%29.aspx
and yes - you'll still want to check its existence with File.Exists
Increment the file name if the file already exists in c#
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);
}
Rename a file in C#
Take a look at System.IO.File.Move, "move" the file to a new name.
System.IO.File.Move("oldfilename", "newfilename");
Rename existing file name
Try to use only:
if (File.Exists("newfilename"))
{
System.IO.File.Delete("newfilename");
}
System.IO.File.Move("oldfilename", "newfilename");
Related Topics
Webdriver How to Wait Until the Element Is Clickable in Webdriver C#
Get Ipv4 Addresses from Dns.Gethostentry()
How to Disable Cascade Delete for Link Tables in Ef Code-First
Add Vertical Scroll Bar to Panel
Simulating Cross Context Joins--Linq/C#
Save Modified Wordprocessingdocument to New File
When Using .Net MVC Radiobuttonfor(), How to Group So Only One Selection Can Be Made
Vertical Text in Wpf Textblock
Using Linq Except Not Working as I Thought
How to Implement "Access-Control-Allow-Origin" Header in ASP.NET
..The Underlying Connection Was Closed: an Unexpected Error Occurred on a Receive
Running Async Methods in Parallel
How to Export a Gridview.Datasource to a Datatable or Dataset
Adding Elements to an Xml File in C#
How to Secure Passwords Stored Inside Web.Config
Giving Application Elevated Uac
Adding Custom Properties for Each Request in Application Insights Metrics