I'm*_*fun 0 c# compare visual-studio
我将两个目录与其中的文件进行比较.一个是旧目录(旧),另一个是新目录(New),其中包含更多文件.我能够打印输出显示所有添加的文件,但它只显示结果文件中我真正希望它去的一个文件.如何让它显示结果文件中添加的所有文件?
Visual Studio上的输出
结果文件中的输出
这是我的代码:
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String New = @"C:\Compare\New";
String Old = @"C:\Compare\Old";
String Result = @"C:\Compare\Result";
DirectoryInfo dir1 = new DirectoryInfo(New);
DirectoryInfo dir2 = new DirectoryInfo(Old);
// Take a look of the file system.
IEnumerable<FileInfo> list1 = dir1.GetFiles("*.*", SearchOption.AllDirectories);
IEnumerable<FileInfo> list2 = dir2.GetFiles("*.*", SearchOption.AllDirectories);
//A custom file comparer defined below
FileCompare compare = new FileCompare();
// Check if same or not.
// bool because of FileCompare
bool areSame = list1.SequenceEqual(list2, compare);
if (areSame == true)
{
MessageBox.Show("The Directories match.");
}
else
{
MessageBox.Show("Directories do not the same.. Please Review 'Result.text'.");
}
// Find the set difference between the two folders.
// Print to the result.txt
var difFromOld = (from file in list1
select file).Except(list2, compare);
foreach (var result in difFromIOld)
{
StreamWriter file = new StreamWriter(Result);
file.WriteLine("The following files do not match between Directories:");
file.WriteLine("");
file.WriteLine(result.Name + "\n", true);
file.Close();
Console.WriteLine(result.Name);
}
}
}
class FileCompare : IEqualityComparer<FileInfo>
{
public FileCompare() { }
public bool Equals(FileInfo f1, FileInfo f2)
{
return (f1.Name == f2.Name && f1.Length == f2.Length);
}
public int GetHashCode(FileInfo fi)
{
string s = String.Format("{0}{1}", fi.Name, fi.Length);
return s.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过foreach循环在每次迭代中创建一个新的StreamWriter.默认情况下,StreamWriter会覆盖文件内容.
最好的解决方案是改变你的循环,看起来像
using(var file = new StreamWriter(Result)) {
foreach (var result in difFromIOld)
{
/* Write to 'file' here */
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以指定StreamWriter应附加到,而不是替换文件:new StreamWriter(Result, append: true).但最好只打开一次文件.
| 归档时间: |
|
| 查看次数: |
672 次 |
| 最近记录: |