A project: find duplicate files
Which files in this folder are copies of each other? A hash of the content answers it, even when the names differ. A project that combines folders, hashing and dictionaries.
What you will learn#
- recursive folder listing,
- content hashes as fingerprints,
- grouping with a dictionary,
- a report that is useful,
- cleaning up after a demo.
The idea#
Two files are the same when their content is the same, whatever their names. Comparing every pair of files byte by byte is slow. A hash (SHA-256) is a short fingerprint of the content: the same content always gives the same hash and different content (practically) never does. So:
- compute the hash of every file,
- put the files in a dictionary keyed by the hash,
- every key with more than one file is a set of duplicates.
The program#
# a project - find duplicate files (folders, hashes, dictionaries)
load "dotnet.ring"
using {
"System"
"System.IO"
"System.Security.Cryptography"
"System.Collections.Generic"
}
func main
# STEP 1. A folder with some files: three of them have the same content, two others as well
cFolder = new Path().Combine([new Path().GetTempPath(),"ringdotnet_duplicates"])
if new Directory().Exists(cFolder)
new Directory().Delete([ :path = cFolder, :recursive = True ])
ok
new Directory().CreateDirectory(cFolder)
new Directory().CreateDirectory(new Path().Combine([cFolder,"old"]))
makeFile(cFolder,"report.txt","Quarterly report: all good.")
makeFile(cFolder,"report copy.txt","Quarterly report: all good.")
makeFile(cFolder,"old/report 2023.txt","Quarterly report: all good.")
makeFile(cFolder,"notes.txt","Remember to buy milk.")
makeFile(cFolder,"todo.txt","Remember to buy milk, and eggs.")
makeFile(cFolder,"old/notes backup.txt","Remember to buy milk.")
? "STEP 1: made six files in a folder and its subfolder"
# STEP 2. Find every file, also in the subfolders
aFiles = new Directory().GetFiles([ :path = cFolder, :searchPattern = "*.txt", :searchOption = "AllDirectories" ]).toList()
? "STEP 2: " + len(aFiles) + " files found"
# STEP 3. The fingerprint of a file is the hash of its content. Same content = same hash.
# A dictionary maps each hash to the files that have it (their paths, joined with | ).
oGroups = new StringDictionary()
for cFile in aFiles
cHash = hashOf(cFile)
aFound = oGroups.TryGetValue(cHash)
if aFound[1]
oGroups.SetItem(cHash,aFound[2] + "|" + cFile)
else
oGroups.SetItem(cHash,cFile)
ok
next
? "STEP 3: " + oGroups.Count + " different contents"
# STEP 4. Report the contents that exist more than once
? nl + "STEP 4: duplicates"
nWasted = 0
aHashes = oGroups.Keys.toList()
for cHash in aHashes
aPaths = str2list(substr(oGroups.Item(cHash),"|",nl))
if len(aPaths) > 1
nSize = new FileInfo(aPaths[1]).Length
nWasted += nSize * (len(aPaths) - 1)
? " " + len(aPaths) + " copies of the same " + nSize + " bytes:"
aSortedPaths = sort(aPaths)
for cPath in aSortedPaths
? " " + substr(cPath,cFolder + "\","")
next
ok
next
? " Space wasted by the extra copies: " + nWasted + " bytes"
# STEP 5. Clean up the demo folder
new Directory().Delete([ :path = cFolder, :recursive = True ])
func makeFile cFolder, cName, cText
cPath = new Path().Combine([cFolder,cName])
new File().WriteAllText([ :path = cPath, :contents = cText ])
# the SHA-256 hash of the content of a file, as text
func hashOf cFile
return lower(new Convert().ToHexString(new SHA256().HashData(new File().ReadAllBytes(cFile))))STEP 1: made six files in a folder and its subfolder
STEP 2: 6 files found
STEP 3: 3 different contents
STEP 4: duplicates
2 copies of the same 21 bytes:
notes.txt
old\notes backup.txt
3 copies of the same 27 bytes:
old\report 2023.txt
report copy.txt
report.txt
Space wasted by the extra copies: 75 bytesHow it works#
Step 1: make test data#
The program creates its own folder with files: three with the same text (one in a subfolder, one with a different name), two with the same other text, and one unique file. A demo that makes its own data runs anywhere and can be checked: the answer is known.
Step 2: list recursively#
Directory.GetFiles([ :path = folder, :searchPattern = "*.txt", :searchOption = "AllDirectories" ]) returns the files of the folder and of every subfolder. "TopDirectoryOnly" would skip the subfolders. The third parameter is an enum, written as a text.
Step 3: hash and group#
hashOf(cFile) reads the bytes (File.ReadAllBytes), hashes them (SHA256.HashData) and writes the hash as hexadecimal text. A StringDictionary maps hash → paths with the paths joined by |: if the hash is known, append the path, else start a new entry. TryGetValue tells which.
Step 4: report#
For each hash with more than one path the program prints the copies and sums the wasted space — the size times the number of extra copies. Sorting the paths makes the report stable.
Cheaper first#
A real tool avoids hashing every file: files with different sizes cannot be equal, so group by size first and hash only the groups with several files. That is exercise 1.
What you learned#
- a hash identifies content,
- a dictionary groups by key,
- recursive listing,
- tests with data that you made yourself.
Exercises#
- Group by file size first; hash only the files whose size occurs more than once.
- Also compare the first 1 MB only for a quick check of very big files.
- Add an option to move duplicates to a
duplicatesfolder instead of just reporting. - Make it a window: a folder box, a Scan button, and the result in a
TreeView(the tutorial Layout and richer controls).