C# – Copying a file with the same name without overwriting
by edy_3dz on May.29, 2011, under Code snippets
I recently encountered a situation where I needed to copy some files over a location where files with the same name already existed, and overwriting them wasn’t an option. So, the following code snippet verifies if a file with the same name already exists, in case which it tries to put a number after the file’s name.
if (File.Exists(path + fileName)
{
int count = 1;
string[] fileNameSplit = fileName.Split(new char[] { '.' });
string ext = "." + fileNameSplit[fileNameSplit.Length - 1];
string prefix = fileName.Substring(0, fileName.Length - ext.Length);
while (File.Exists(path + fileName))
{
fileName = prefix + "(" + count.ToString() + ")" + ext;
count++;
}
File.Copy(source, path + fileName);
}
else
{
File.Copy(source, path + fileName);
}
I hope that you’ll find this helpful
June 20th, 2011 on 10:18
Just what i need,thank you!!!
January 20th, 2012 on 01:13
Good info! Keep it comin’!