Nick
Nick

Reputation: 10499

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?

Upvotes: 2

Views: 626

Answers (2)

gliderkite
gliderkite

Reputation: 8928

The easiest way I know is the one that makes use of Path and File classes, in the System.IO namespace.

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

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:

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.

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:

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

Upvotes: 3

Habib
Habib

Reputation: 223322

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

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?

Upvotes: 1

Related Questions