Requires NuGet package Spectre.Console for return text.
Created
April 7, 2025 10:20
-
-
Save karenpayneoregon/6edc2ba4f21b13bca8922863e28ca660 to your computer and use it in GitHub Desktop.
Update Framework in project file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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