我有一个文件:
string myFile = @"C:\Users\Nick\Desktop\myFile.txt";
我想检查另一个目录中是否有这个文件的副本:
string DestinationDir = @"C:\Users\Nick\Desktop\MyDir"
我怎样才能做到这一点?
我知道的最简单的方法是在System.IO命名空间中使用Path和File类。
您可以使用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 个文件?