3dz Soft

C# – Copying a file with the same name without overwriting

by 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 :)


2 Comments for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!