2016-07-01 109 views
0

假设我有一个文件夹,并在此文件夹中是一个名为im1.png的图像。我想im1.png被删除,当我保存另一个图像名为im1.jpgim1.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; 
    } 
+0

不相关的问题,但你并不需要检查'Directory.Exists(curpath)' ,只需调用'Directory.CreateDirectory(curpath);'每一次,如果目录已经存在,函数什么也不做(实际上,它实际上会返回现有目录的'DirectoryInfo'对象,但是你没有使用函数的结果,所以对于你的用例它什么都不做)。 –

+0

@Scott Chamberlain:谢谢,我编辑了我的问题。这段代码会检查一个文件是否已经存在。我的问题是文件不与目录。 – Saeid

回答

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); 
+0

非常感谢。我对你的答案做了一些修改,但是我有下面的例外!你的答案似乎是正确的,但我不知道为什么我有一个例外!我用这段代码编辑了我的问题。请看看。 '(“该进程无法访问文件'E:\ FaceAuthentication \ FaceApp \ bin \ Debug \ FaceApp.App \ FaceDBIMG \ 23 \ 5.jpg',因为它正在被另一个进程使用。”)\t' – Saeid

+0

你是目前使用这个文件(5.jpg)? –

+0

根本不是.... – Saeid

相关问题