0

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

4

3 回答 3

1

我会尝试以下功能,它远非完美:

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

更新:

另一种方法是读出 ByteArray 这将解决图像问题。但是随着时间的推移,该功能仍然会变慢。

    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;
    }
于 2015-06-24T15:04:56.997 回答
1

您需要使用 system.io 命名空间检查目标文件夹,例如:

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

您可以将模式添加到 getfiles 函数,前提是它发现文件与它返回的模式匹配。

于 2015-06-24T15:08:14.673 回答
0

尝试比较文件哈希。这是一个例子:

        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);
        }
于 2015-06-24T15:14:23.163 回答