Automatically rename a file if it already exists in Windows way

[Originally Posted From] : http://stackoverflow.com/questions/13049732/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);
}
shareedit

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s