Skip to content

Instantly share code, notes, and snippets.

@Pzixel
Created December 6, 2019 14:59
Show Gist options
  • Save Pzixel/4a405e80861c4d321ef85ab46a71f948 to your computer and use it in GitHub Desktop.
Save Pzixel/4a405e80861c4d321ef85ab46a71f948 to your computer and use it in GitHub Desktop.
void Main()
{
var files = Directory.EnumerateFiles(@"C:\Users\me\Documents\Repos\myrepo\", "*.csproj", SearchOption.AllDirectories);
foreach (var csprojPath in files)
{
PatchCsProj(csprojPath);
}
}
void PatchCsProj(string path)
{
var directory = Path.GetDirectoryName(path);
var oldCsProj = File.ReadAllText(path);
if (oldCsProj.Contains("<TargetFramework>net45</TargetFramework>"))
{
return;
}
var packagesPath = Path.Combine(directory, "packages.config");
var packagesconfig = File.Exists(packagesPath) ? File.ReadAllText(packagesPath) : string.Empty;
var packages = Regex.Matches(packagesconfig, "id=\"([^\"]+)\"\\s+version=\"([^\"]+)\"").Cast<Match>().Select(m => new {Name = m.Groups[1].Value, Version = m.Groups[2].Value})
.Where(m => !m.Name.StartsWith("System")).ToArray();
var projectReferences = Regex.Matches(oldCsProj, "ProjectReference Include=\"([^\"]+)\"").Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
//(packages, projectReferences).Dump();
const string csprojTemplate = @"<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<TargetFramework>net45</TargetFramework>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<ItemGroup>
{0}
</ItemGroup>
<ItemGroup>
{1}
</ItemGroup>
</Project>";
var sdkPackages = string.Join(Environment.NewLine, packages.Select(p => $" <PackageReference Include=\"{p.Name}\" Version=\"{p.Version}\" />"));
var sdkProjectReferences = string.Join(Environment.NewLine, projectReferences.Select(pr => $" <ProjectReference Include=\"{pr}\" />"));
var resultingCsProj = string.Format(csprojTemplate, sdkPackages, sdkProjectReferences);
File.WriteAllText(path, resultingCsProj);
File.Delete(packagesPath);
Directory.Delete(Path.Combine(directory, "Properties"), true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment