如果文件存在则删除另一个文件

时间:2014-12-06 13:58:37

标签: c# file if-statement exists delete-file

我需要在存在其他文件时删除文件。

Directory.GetFiles(dirName)
     .Select(f => new FileInfo(f))
     .Where(f => f.exists)
     .ToList()
     .ForEach(f => f.Delete());     

这是自动删除文件的工作代码,但我需要修改它以删除其他目录中的其他文件。

directory2中的文件名称略有不同。 directory1中的文件名= MyFileName() 但是directory2中的文件名= MyFileName

E.g。在" C:// folder123" 存在文件" File123()"      我需要在" C://我的文档/文件夹456" 中检测到并删除文件" File123"

//修改

我已经写了一些东西,我认为它应该可行,但我必须弄清楚应用程序池的问题来测试它:

string path = "directory2";
        Directory.GetFiles("directory1")
        .Where(f => f.Contains("()") == true)
        .Select(f => f.TrimEnd(')', '('))
        .ToList();
        File.Delete(path);    

1 个答案:

答案 0 :(得分:0)

这个解决方案怎么样?

string sourcePath = "c:\\folder123\file123()";
string secondPath = "c:\\documents\\folder456";

if(File.Exists(sourcePath))
{
    FileInfo sInfo = new FileInfo(sourcePath);
    string dFilePath = Path.Combine(secondPath, sInfo.Name.Replace("()",""));
    if(File.Exists(dFilePath))
        File.Delete(dFilePath);
}
我把它写在我的iPad上,所以我希望它是对的。也许字符串"()"需要逃脱字符。

相关问题