Wednesday, October 31, 2018

GetUniqueFilename Method to rename a file if it exits

 private static string GetUniqueFilename(string fullPath)
        {
            if (!Path.IsPathRooted(fullPath))
                fullPath = Path.GetFullPath(fullPath);

            if (File.Exists(fullPath))
            {
                string filename = System.IO.Path.GetFileName(fullPath);
                string path = fullPath.Substring(0, fullPath.Length - filename.Length);
                string filenameWOExt = System.IO.Path.GetFileNameWithoutExtension(fullPath);
                string ext = System.IO.Path.GetExtension(fullPath);
                int n = 1;

                do
                    fullPath = System.IO.Path.Combine(path, string.Format("{0} ({1}){2}", filenameWOExt, (Math.Min(System.Threading.Interlocked.Increment(ref n), n - 1)), ext));
                while (File.Exists(fullPath));
            }

            return fullPath;
        }

No comments:

Post a Comment