C# - How do I check if a file exists in a certain directory (based on its content, not the file name)?

2.4k views Asked by At

I am creating a program that will grab files from a Result Directory (Original Folder) and move those files to a Working Directory (Another Folder). Here the file's name is being changed when the file is moved from one directory to another. Before I move them, I need to check that the Working Directory does not contain that file I am trying to move already. Since the file name is being changed, I need something that will check if the file exists already based on the content inside of the file.

Let's say I have:

FilesRD - (The files in the Original Folder/Result Directory)
FilesWD - (The files in the Other Folder/Working Directory)

and the files inside of those directories will look like this...

Before (In Result Directoy):
Log_123.csv

After (In Working Directory):
Log_123_2015_24_6.csv

3

There are 3 answers

4
Xanatos On BEST ANSWER

I would try the following function it's far from being perfect:

    private bool CheckIfFileAlreadyExist(string WorkingDirectory, string FileToCopy)
    {
        string FileToCheck = File.ReadAllText(FileToCopy);
        foreach (string CurrentFile in Directory.GetFiles(WorkingDirectory))
        {
            if (File.ReadAllText(CurrentFile) == FileToCheck)
                return true;
        }
        return false;
    }

UPDATE:

Another way is to read out the ByteArray this would solve the Image Problem. But the function still get's slow over time.

    private bool CheckIfFileAlreadyExist(string WorkingDirectory, string FileToCopy)
    {
        byte[] FileToCheck = File.ReadAllBytes(FileToCopy);
        foreach (string CurrentFile in Directory.GetFiles(WorkingDirectory))
        {
            if (File.ReadAllBytes(CurrentFile) == FileToCheck)
                return true;
        }
        return false;
    }
3
Proxytype On

you need to check in the destination folder using system.io namespace for example:

string destination = "c:\myfolder\"; 
string [] files   Directory.GetFiles(destination , "Log_123");
if(files.Length == 0)
{
   //move the file to the directory
}

you can add pattern to the getfiles function, only if it found file match to the pattern it's return it.

1
Jyrka98 On

Try comparing the files hashes. Here's an example:

        private static string GetFileMD5(string fileName) {
            using (var md5 = MD5.Create()) {
                using (var fileStream = File.OpenRead(fileName)) {
                    return BitConverter.ToString(md5.ComputeHash(fileStream)).Replace("-", "").ToLower();
                }
            }
        }
        private static bool DoesFileExist(string workingDir,string fileName) {
            var fileToCheck = GetFileMD5(fileName);
            var files = Directory.EnumerateFiles(workingDir);
            return files.Any(file => string.Compare(GetFileMD5(file), fileToCheck, StringComparison.OrdinalIgnoreCase) == 0);
        }