Skip to content

Instantly share code, notes, and snippets.

@nzbart
Last active June 25, 2016 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nzbart/8190533 to your computer and use it in GitHub Desktop.
Save nzbart/8190533 to your computer and use it in GitHub Desktop.
A simple and naive C# program that will help identify binary file types in a directory.
/*
* Recommended usage is to pipe in a list of paths :
* Git:
* git ls-files | FindBinaryFiles.exe
* PowerShell:
* ls -r | ? PSIsContainer | select -expand FullName | FindBinaryFiles.exe
* */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
var files = GetFileListFromStdin()
.Select(f => f.ToUpperInvariant())
.Where(NotExcluded)
.GroupBy(Path.GetExtension)
.OrderBy(g => g.Key)
.Where(g => g.Key.Length != 0);
Console.WriteLine("Binary files:");
foreach (var extn in files)
{
if (extn.Any(IsBinaryFile))
{
Console.WriteLine(extn.Key);
}
}
}
static IEnumerable<string> GetFileListFromStdin()
{
string s;
while ((s = Console.ReadLine()) != null)
{
yield return s;
}
}
static bool NotExcluded(string fullPath)
{
var exclude = new[] { @"\\ThirdParty\\", @"\\bower_components\\", @"\\node_modules\\" };
return !exclude.Any(ex => Regex.IsMatch(fullPath, ex, RegexOptions.IgnoreCase));
}
static bool IsBinaryFile(string fullPath)
{
using (var file = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 10240, FileOptions.SequentialScan))
{
while (true)
{
int currentByte = file.ReadByte();
if (currentByte == -1)
return false;
if (currentByte == 0)
return true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment