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.
public static void FileCopyWithoutOverwriting(string sourceFile, string fileName, string destinationPath)
{
// if destinationPath doesn't add with a slash, add one
if ((destinationPath.EndsWith("\\") || destinationPath.EndsWith("/")) == false)
destinationPath += "\\";
try
{
// if file already exists in destination
if (File.Exists(destinationPath + fileName))
{
// counter
int count = 1;
// extract extension
FileInfo info = new FileInfo(sourceFile);
string ext = info.Extension;
string prefix;
// if it has an extension, append it to a .
if (ext.Length > 0)
{
// get filename without extension
prefix = fileName.Substring(0, fileName.Length - ext.Length);
ext = "." + ext;
}
else
prefix = fileName;
// while not found an valid destination file name, increase counter
while (File.Exists(destinationPath + fileName))
{
fileName = prefix + "(" + count.ToString() + ")" + ext;
count++;
}
// copy file
File.Copy(sourceFile, destinationPath + fileName);
}
else
{
File.Copy(sourceFile, destinationPath + fileName);
}
Console.WriteLine("File copy done.");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("The caller does not have the required permission.");
}
catch (ArgumentException)
{
Console.WriteLine("One of the arguments is invalid.");
}
catch (PathTooLongException)
{
Console.WriteLine("The specified path, file name, or both exceed the system-defined maximum length.");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("At least one of the specified paths are invalid.");
}
catch (FileNotFoundException)
{
Console.WriteLine("{0} was not found", sourceFile);
}
catch (IOException)
{
Console.WriteLine("An I/O error has occurred.");
}
catch (NotSupportedException)
{
Console.WriteLine("Source filename is in invalid format.");
}
}
I hope that you’ll find this helpful
UPDATE: A made a better version, with exception handling too.
June 20th, 2011 on 10:18
Just what i need,thank you!!!
January 20th, 2012 on 01:13
Good info! Keep it comin’!