Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created April 7, 2025 10:20
Show Gist options
  • Save karenpayneoregon/6edc2ba4f21b13bca8922863e28ca660 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/6edc2ba4f21b13bca8922863e28ca660 to your computer and use it in GitHub Desktop.
Update Framework in project file
using System.Xml.Linq;
namespace UpdateFrameworkApp.Classes;
public class ProjectUpdater
{
public static string UpdateTargetFramework(string csprojPath, string oldFramework = "net7.0", string newFramework = "net9.0")
{
if (!File.Exists(csprojPath))
{
return $"[red]File not found:[/] {csprojPath}";
}
try
{
var doc = XDocument.Load(csprojPath);
var targetFrameworkElement = doc.Root?.Element("PropertyGroup") ?.Element("TargetFramework");
if (targetFrameworkElement == null)
{
return "[red]No <TargetFramework> element found.[/]";
}
if (targetFrameworkElement.Value.Trim() != oldFramework)
{
return $"[red]TargetFramework is not[/] [cyan]'{oldFramework}'[/],[red] found[/] [cyan]'" +
$"{targetFrameworkElement.Value}'[/]. [red]No changes made.[/]";
}
targetFrameworkElement.Value = newFramework;
doc.Save(csprojPath);
return $"[cyan]Updated TargetFramework to[/] '{newFramework}' [cyan]in[/] '{Path.GetFileName(csprojPath)}'.";
}
catch (Exception ex)
{
return $"Error updating file: {ex.Message}";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment