Skip to content

Instantly share code, notes, and snippets.

@forensicmike
Last active March 11, 2019 13:23
Show Gist options
  • Select an option

  • Save forensicmike/9aeda99e0e0371eaaea800545b1c5e02 to your computer and use it in GitHub Desktop.

Select an option

Save forensicmike/9aeda99e0e0371eaaea800545b1c5e02 to your computer and use it in GitHub Desktop.
LINQPad script to iterate SQLite DBs in a directory given one of any number of extensions and run a query, present grouped results using .Dump()
// PREREQUISITES - Install NuGet packages for Sqlite3 and Newtonsoft.JSON
void Main()
{
// What is our base directory? Remember, we will traverse subfolders as well
var sourceDirectory = @"c:\temp\";
// What extensions are we after? IDK if this is case sensitive or not
var extensions = new List<string>(new string[] { "*.sqlite", "*.db" });
// What SQL Query do we want to run?
var sqlQuery = "SELECT * FROM sqlite_master WHERE type='table';";
// This does a concatenation of Directory.GetFiles on each of the allowed extensions found within sourceDirectory
var fileList = extensions.SelectMany(x => Directory.GetFiles(sourceDirectory, x, SearchOption.AllDirectories));
// Store our results here
var results = new Dictionary<string, List<dynamic>>();
// Every file we found
foreach (var db in fileList)
{
// Open the DB
using (var con = new SQLiteConnection($"Data Source={db}"))
{
con.Open();
// Who needs error checking?
// Setup a results key for our dictionary, use the full path to avoid name collisions
results.Add(db, new List<dynamic>());
// Our cmd has to be paired to the now open connection
var cmd = new SQLiteCommand(sqlQuery, con);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// This next bit of code is woefully inefficient, but will serve our purpose today
var objDict = new Dictionary<string,object>();
for (int i = 0; i < reader.FieldCount; i++)
{
objDict.Add(reader.GetName(i), reader.GetValue(i));
}
// Got to love JsonConvert
var data = JsonConvert.SerializeObject(objDict);
results[db].Add(data);
}
reader.Close();
}
con.Close();
}
}
results.Dump();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment