繁体   English   中英

检查一个文件夹是否包含一个文件,该文件是另一个文件夹中文件的副本

[英]Check if a folder contains a file that is a copy of a file in another folder

我有一个文件:

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

我想检查另一个目录中是否存在此文件的副本:

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

我该如何实现?

我知道的最简单的方法是在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 ...
}

这里的文章介绍了如何使用FileStream比较两个文件。

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

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

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

检查此线程: 如何使用.NET快速比较2个文件?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM