4.11. Comparing Files or Folders

Problem

You want to compare the contents of two files or two folders to determine the differences.

Solution

Using a graphical user interface

  1. Open the WinDiff application (windiff.exe) from the Resource Kit.

  2. To compare two files, select File Compare Files from the menu. To compare two directories, select File Compare Directories.

Using a command-line interface

The fc.exe command compares two or more files:

> fc <File1Path> 
                  <File2Path>

Here is an example:

> fc c:\netdiag.log c:\old\netdiag.log

To compare two binary files, include the /b option in the previous command.

Using VBScript

' This code compares the contents of two text-based files.
' ------ SCRIPT CONFIGURATION ------
strFile1 = "<FilePath1>"  ' e.g., c:\scripts\test1.vbs
strFile2 = "<FilePath2>"  ' e.g., c:\scripts\test2.vbs
' ------ END CONFIGURATION ---------
set objFSO = CreateObject("Scripting.FilesystemObject")
set objFile1 = objFSO.opentextfile(strFile1,1)
set objFile2 = objFSO.opentextfile(strFile2,1)
arrFile1 = split(objFile1.ReadAll,vbNewLine)
arrFile2 = split(objFile2.ReadAll,vbNewLine)
objFile1.close
objFile2.close
   
if ubound(arrFile1) < ubound(arrFile2) then
   intLineCount = ubound(arrFile1)
   strError = strFile2 & " is bigger than " & strFile1
elseif ubound(arrFile1) > ubound(arrFile2) then
   intLineCount = ubound(arrFile2)
   strError = strFile2 & " is bigger than " & strFile1
else 
   intLineCount = ubound(arrFile2)
end if
   
for i = 0 to intLineCount
   if not arrFile1(i) = arrFile2(i) then 
      exit for
   end if
next
   
if i < (intLineCount + 1) then
   WScript.Echo "Line " & (i+1) & " not equal"
   WScript.Echo strError
elseif strError <> "" then
   WScript.Echo strError
else 
   WScript.Echo "Files are identical."
end if

Discussion

Of all of the methods I described, Windiff is by far the smartest in terms of identifying when lines have been added to a file or a section of text has been moved around. By comparison, the VBScript isn't nearly as robust. It simply checks line by line to determine if two text files are identical.

See Also

MS KB 159214 (How to Use the Windiff.exe Utility)

Get Windows Server Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.