Сравнение файлов с использованием C#

Опубликовано: 10 Января, 2023

C# — это современный объектно-ориентированный язык программирования общего назначения, произносимый как «C Sharp», на котором мы можем создавать файлы. Иногда нам нужно выполнять операции над файлом. Эта операция может быть чем угодно: от побайтового сравнения файлов до необходимости проверки дат или длины файлов.

Для этого у нас есть несколько классов, таких как FileStream, FileInfo, которые входят в пространство имен System.IO.

Чтобы выполнить сравнение файлов:

Для сравнения файлов у нас есть несколько вариантов, либо мы можем сделать файловый поток и проверять файл побайтно. C# имеет один класс FileInfo, который также можно использовать для сравнения длины или даты их создания. FileInfo является запечатанным классом, что означает, что он не может быть унаследован. Здесь мы собираемся использовать два класса FileStream и FileInfo для сравнения.

public sealed class FileInfo : System.IO.FileSystemInfo

public class FileStream : System.IO.Stream

Пример 1:

C#




// Use FileInfo Class in C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace FileInfo1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            FileInfo f1 = new FileInfo(@"C: est est1.txt");
            FileInfo f2 = new FileInfo(@"C: est est2.txt");
             
            // checking the size of files
            if(f1.Length != f2.Length)
            {
                Console.WriteLine("File sizes are not equal");
            }
            else
            {
                Console.WriteLine("File sizes are equal");
            }
            //for getting Creation time
            Console.WriteLine("first file creation date is " + f1.CreationTime);
            Console.WriteLine("second file creation date is " + f2.CreationTime);
 
            //For getting parent directory
            Console.WriteLine("first file parent Directory is " + f1.Directory);
            Console.WriteLine("second file parent Directory is " + f2.Directory);
            Console.Read();
        }
    }
}

Выход:

Пример 2:

C#




// Use FileStream Class in C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace use_file_stream
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string path1 = @"C: est est1.txt";
            string path2 = @"C: est est2.txt";
 
            using(FileStream fs1 = new FileStream(path1, FileMode.Open),
                  fs2 = new FileStream(path2, FileMode.Open))
            {
                int c1 = 0;
                int c2 = 0;
                do
                {
                    c1 = fs1.ReadByte();
                    c2 = fs2.ReadByte();
                }
                while (c1 == c2 && c1!=-1 && c2!=-1);
 
                if (c1 == c2)
                {
                    Console.WriteLine("Files are equal");
                }
                else{
                    Console.WriteLine("Files are not equal");
                }
                Console.ReadLine();
            }
            
        }
 
    }
}

Выход: