Skip to content

Instantly share code, notes, and snippets.

@hoangitk
Forked from shawnwildermuth/CleanVS.csx
Created June 8, 2017 06:44
Show Gist options
  • Save hoangitk/3cb9241da3fd3af5ad7bb8255ee3a7a5 to your computer and use it in GitHub Desktop.
Save hoangitk/3cb9241da3fd3af5ad7bb8255ee3a7a5 to your computer and use it in GitHub Desktop.
A ScriptCS script that will clean a Visual Studio project directory of files that I don't need. (Think of it as an ignore file that deletes the actual files).
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Diagnostics;
Console.WriteLine("Cleaning current folder and subfolders");
Console.WriteLine();
var toDelete = new [] { "bin","obj","bld","Backup","_UpgradeReport_Files","Debug","Release,ipch","*.mdf","*.ldf","*.suo","Packages","bower_components","node_modules","lib",".vs","artifacts" };
var originalConsoleColor = Console.ForegroundColor;
long cleanedSpace = 0;
var errors = new List<string>();
var currentDir = new DirectoryInfo(Directory.GetCurrentDirectory());
foreach (var srch in toDelete)
{
Console.Write("{0} ", srch);
var candidates = currentDir.GetFileSystemInfos(srch, SearchOption.AllDirectories);
foreach (var candidate in candidates)
{
Console.ForegroundColor = ConsoleColor.Red;
try
{
if (candidate is DirectoryInfo)
{
var info = (DirectoryInfo)candidate;
if (Directory.Exists(info.FullName))
{
var size = info.GetFiles("*.*", SearchOption.AllDirectories).Sum(file => file.Length);
DeleteLongDirectory(info);
cleanedSpace += size;
}
}
else
{
var info = (FileInfo)candidate;
var size = info.Length;
info.Delete();
cleanedSpace += size;
}
Console.Write(".");
}
catch (Exception ex)
{
errors.Add(ex.Message);
Console.Write("x");
}
}
Console.ForegroundColor = originalConsoleColor;
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("Cleaned...Saved {0:d}mb", cleanedSpace / 1024 / 1024);
if (errors.Count() > 0)
{
Console.WriteLine();
Console.WriteLine("Likely you have problems with long-paths (e.g. node_modules)");
foreach (var err in errors) Console.WriteLine("Error Occurred: {0}", err);
}
void DeleteLongDirectory(DirectoryInfo info)
{
try
{
info.Delete(true);
}
catch
{
// If delete not working (long paths usually), try RimRaf
var procInfo = new ProcessStartInfo($"rimraf", $"{info.FullName}")
{
UseShellExecute = false
};
var proc = Process.Start(procInfo);
proc.WaitForExit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment