简体   繁体   English

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

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

I have a file: 我有一个文件:

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

And I want to check if there is a copy of this file in another directory: 我想检查另一个目录中是否存在此文件的副本:

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

How can I achieve this? 我该如何实现?

The easiest way I know is the one that makes use of Path and File classes, in the System.IO namespace. 我知道的最简单的方法是在System.IO命名空间中使用PathFile类的方法。

You could use the Path.Combine method to combine the path of the your destination directory with the name of the file to find (returned by Path.GetFileName method): 您可以使用Path.Combine方法将目标目录的路径与要查找的文件名结合在一起(由Path.GetFileName方法返回):

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

At this point you could simply check if dest_file exist with File.Exists method: 此时,您可以使用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 an article that explains how to compare two files using FileStream. 这里的文章介绍了如何使用FileStream比较两个文件。

There is also an alternative to check if the file exist in the destination directory, take a look at the Directory class, in particular to the method Directory.GetFiles : 还有一种方法可以检查文件是否存在于目标目录中,请查看Directory类,尤其是Directory.GetFiles方法:

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

Extract the file name from the myFile , use Path.Combine to create new path for DestinationDir + your filename and then, check if the file exists, using File.Exists myFile提取文件名,使用Path.Combine为DestinationDir +您的文件名创建新路径,然后使用File.Exists检查文件是否存在。

For comparing two files try: 要比较两个文件,请尝试:

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

Check this thread: How to compare 2 files fast using .NET? 检查此线程: 如何使用.NET快速比较2个文件?

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

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