반응형
        public static bool CopyFileAsUniqueName(string srcFilePath, string destFilePath)
        {
            try
            {
                if (File.Exists(srcFilePath) == false)
                {
                    return false;
                }

                destFilePath = GetUniqueFilePath(destFilePath);

                File.Copy(srcFilePath, destFilePath, true);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static string GetUniqueFilePath(string filePath)
        {
            string dirPath = GetDirectoryPath(filePath);

            string newFileName = GetUniqueFileName(filePath, GetFileName(filePath));

            return Path.Combine(dirPath, newFileName);
        }

        public static string GetUniqueFileName(string filePath, string filename, int i = 0)
        {
            string lstDir = filePath.Substring(0, filePath.LastIndexOf('\\'));
            string name = Path.GetFileName(filePath);
            string path = filePath;

            if (name != filename)
                path = Path.Combine(lstDir, filename);

            if (System.IO.File.Exists(path))
            {
                string ext = Path.GetExtension(name);
                name = Path.GetFileNameWithoutExtension(name);
                i++;
                filename = GetUniqueFileName(filePath, $"{name}_({i}){ext}", i);
            }

            return filename;
        }
반응형

+ Recent posts