它关于将图像文件从一个目录复制到另一个目录

时间:2013-08-19 06:03:54

标签: c#

我有3个目录。这些是好的,坏的图像。我从图像目录中获取图像,然后将其发送到其他目录。我的问题是,如果好的或坏的目录有这些图像我怎么能改变图像的名称,如“我有car.jpg,如果我再次复制,它的名称改为car(1).jpg。我希望你理解我的问题..

2 个答案:

答案 0 :(得分:1)

我使用这样的代码

internal static partial class IOUtilities
{
    /// <summary>
    /// Move a file to an archive folder
    /// </summary>
    /// <remarks>Renames file if necessary to avoid collision.
    /// See <see cref="File.Move"/> for exceptions</remarks>
    /// <param name="file">path to file to move</param>
    /// <param name="targetFolder">folder to move file to</param>
    public static void ArchiveFile(string file, string targetFolder) {
        if (file == null)
            throw new ArgumentNullException("file");
        if (targetFolder == null)
            throw new ArgumentNullException("targetFolder");

        string targetFilename = Path.Combine(targetFolder, Path.GetFileName(file));
        File.Move(file, FindAvailableFilename(targetFilename));
    }

    /// <summary>
    /// Archive file in the same folder
    /// </summary>
    /// <remarks>Renames file by adding first free "(n)" suffix
    /// See <see cref="File.Move"/> for exceptions</remarks>
    /// <param name="file">path to file to archive</param>
    public static void ArchiveFile(string file) {
        if (file == null)
            throw new ArgumentNullException("file");

        File.Move(file, FindAvailableFilename(file));
    }

    /// <summary>
    /// Find a "free" filename by adding (2),(3)...
    /// </summary>
    /// <param name="targetFilename">Complete path to target filename</param>
    /// <returns>First available filename</returns>
    private static string FindAvailableFilename(string targetFilename) {
        if (!File.Exists(targetFilename))
            return targetFilename;

        string filenameFormat = Path.GetFileNameWithoutExtension(targetFilename) + "({0})" + Path.GetExtension(targetFilename);
        string format = Path.Combine(Path.GetDirectoryName(targetFilename), filenameFormat);
        for (int ii = 2;; ++ii) {
            // until we find a filename that doesn't exist
            string newFilename = string.Format(CultureInfo.InvariantCulture, format, ii);
            if (!File.Exists(newFilename)) // returns false on illegal paths, security problems etc
                return newFilename;
        }
    }
}

答案 1 :(得分:0)