Skip to content

Instantly share code, notes, and snippets.

@marta-krzyk-dev
Last active April 17, 2019 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marta-krzyk-dev/00f49f159a16967cfa6b87942ba66f74 to your computer and use it in GitHub Desktop.
Save marta-krzyk-dev/00f49f159a16967cfa6b87942ba66f74 to your computer and use it in GitHub Desktop.
Upgrade .NET Framework version in all projects at once
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace UpgradeFrameworkInProjects
{
class Program
{
private const string exitCode = "0";
private const string defaultFolderPath = @"C:\Solutions\MySolution";
private const string defaultFrameworkVersion = "v4.6.1";
static void Main(string[] args)
{
while (UpgradeFrameworkInProjects())
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Press any key to restart.");
Console.WriteLine($"Type {exitCode} to exit the program.");
Console.ReadKey();
}
}
private static bool UpgradeFrameworkInProjects()
{
Console.WriteLine("---");
Console.WriteLine("This program updates .NET Framework version in all projects in a solution.\n");
Console.WriteLine($"Hit enter to run in this solution: {defaultFolderPath}");
Console.Write("Or enter path to solution folder: ");
string folderPath = Console.ReadLine().Trim();
if (string.IsNullOrWhiteSpace(folderPath))
folderPath = defaultFolderPath;
else if (folderPath == exitCode)
return false;
Console.WriteLine($"Hit enter to update projects to version: {defaultFrameworkVersion}");
Console.Write("Or enter the version: v");
string newVersion = Console.ReadLine().Trim();
if (string.IsNullOrWhiteSpace(newVersion))
newVersion = defaultFrameworkVersion;
else if (newVersion == exitCode)
return false;
if (newVersion.ToLower().StartsWith("v"))
newVersion = newVersion.Remove(0, 1);
int count = 0;
try
{
string[] files = Directory.GetFiles(folderPath, "*.csproj", SearchOption.AllDirectories);
foreach (var file in files)
{
string text = File.ReadAllText(file);
string pattern = @"<\s*TargetFrameworkVersion\s*>v([\d\.]+)<\/\s*TargetFrameworkVersion\s*>";
text = Regex.Replace(text, pattern, $"<TargetFrameworkVersion>v{newVersion}</TargetFrameworkVersion>");
File.WriteAllText(file, text);
Console.WriteLine($"{++count}. Updated {file.Split('\\').LastOrDefault()}");
}
}
catch (Exception exception)
{
Console.WriteLine($"Error: {exception.Message}");
}
Console.WriteLine();
Console.WriteLine($"Updated Framework version in {count} projects.");
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment