Automatically Rename a File If It Already Exists in Windows Way

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



Leave a reply



Submit