如何替换文件夹中具有相同名称但不同类型的另一图像的图像?

时间:2016-07-01 20:22:13

标签: c#

假设我有一个文件夹,在此文件夹中是一个名为im1.png的图像。我希望在此文件夹中保存另一个名为im1.pngim1.jpg左右的图像(同名但不同类型)时删除im1.bmp。我写下面的代码,但这段代码只删除具有相同名称和相同类型的文件。请帮帮我......

string CopyPic(string MySourcePath, string key, string imgNum)
    {
        string curpath;
        string newpath;

        curpath = Application.Current + @"\FaceDBIMG\" + key;

        if (Directory.Exists(curpath) == false)
            Directory.CreateDirectory(curpath);

        newpath = curpath + "\\" + imgNum + MySourcePath.Substring(MySourcePath.LastIndexOf("."));

        string[] similarFiles = Directory.GetFiles(curpath, imgNum + ".*").ToArray();

        foreach (var similarFile in similarFiles)
            File.Delete(similarFile);

        File.Copy(MySourcePath, newpath);

        return newpath;
    }

1 个答案:

答案 0 :(得分:2)

这是一种方法:

string filename = ...; //e.g. c:\directory\filename.ext

//Get the directory where the file lives
string dir = Path.GetDirectoryName(filename);

//Get the filename without the extension to use it to search the directory for similar files
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(filename);

//Search the directory for files with same name, but with any extension
//We use the Except method to remove the file it self form the search results
string[] similarFiles =
    Directory.GetFiles(dir, filenameWithoutExtension + ".*")
    .Except(
        new []{filename},
        //We should ignore the case when we remove the file itself
        StringComparer.OrdinalIgnoreCase)
    .ToArray();

//Delete these files
foreach(var similarFile in similarFiles)
    File.Delete(similarFile);