【问题标题】:Check if a folder contains a file that is a copy of a file in another folder检查文件夹是否包含一个文件,该文件是另一个文件夹中文件的副本
【发布时间】:2012-06-03 16:44:03
【问题描述】:

我有一个文件:

string myFile = @"C:\Users\Nick\Desktop\myFile.txt";

我想检查另一个目录中是否有这个文件的副本:

string DestinationDir = @"C:\Users\Nick\Desktop\MyDir"

我怎样才能做到这一点?

【问题讨论】:

    标签: .net file directory copy


    【解决方案1】:

    我知道的最简单的方法是在 System.IO 命名空间中使用 PathFile 类。

    您可以使用Path.Combine 方法将目标目录的路径与要查找的文件名结合起来(由Path.GetFileName 方法返回):

    string dest_file = Path.Combine(dest_dir, Path.GetFileName(source_file));
    

    此时您可以简单地使用File.Exists 方法检查dest_file 是否存在:

    if (File.Exists(dest_file))
    {
       // You can get file properties using the FileInfo class
       FileInfo info_dest = new FileInfo(dest_file);
       FileInfo info_source = new FileInfo(source_file);
    
       // And to use the File.OpenRead method to create the FileStream
       // that allows you to compare the two files
       FileStream stream_dest = info_dest.OpenRead();
       FileStream stream_source = info_source.OpenRead();
    
       // Compare file streams here ...
    }
    

    Here 一篇介绍如何使用 FileStream 比较两个文件的文章。

    还有一种方法可以检查文件是否存在于目标目录中,看看Directory类,特别是方法Directory.GetFiles

    foreach (string dest_file in Directory.GetFiles(dest_dir))
    {
        // Compare dest_file name with source_file name
        // and so on...
    }
    

    【讨论】:

    • 谢谢,真正全面的回复。
    【解决方案2】:

    myFile 中提取文件名,使用Path.Combine 为DestinationDir + 您的文件名创建新路径,然后使用File.Exists 检查文件是否存在

    比较两个文件试试:

    public static IEnumerable<string> ReadLines(string path)
    public static IEnumerable<string> ReadLines(string path, Encoding encoding)
    bool same = File.ReadLines(path1).SequenceEqual(File.ReadLines(path2));
    

    查看这个帖子:How to compare 2 files fast using .NET?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 2017-08-28
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      相关资源
      最近更新 更多