Here's a straightforward C# class that reads a .csproj file and provides two methods:
Exists() — Checks if the node exists.
GetValue() — Returns the value of the if present.
This implementation uses System.Xml.Linq for simplicity and readability.
✅ CsProjSecretsReader.cs
using System;
using System.IO;
using System.Xml.Linq;
public class CsProjSecretsReader
{
private readonly string _csprojFilePath;
private readonly XDocument _projectXml;
public CsProjSecretsReader(string csprojFilePath)
{
if (string.IsNullOrWhiteSpace(csprojFilePath))
throw new ArgumentException("Path to .csproj file must be provided.");
if (!File.Exists(csprojFilePath))
throw new FileNotFoundException("The .csproj file was not found.", csprojFilePath);
_csprojFilePath = csprojFilePath;
_projectXml = XDocument.Load(_csprojFilePath);
}
public bool Exists()
{
return GetUserSecretsElement() != null;
}
public string? GetValue()
{
var element = GetUserSecretsElement();
return element?.Value;
}
private XElement? GetUserSecretsElement()
{
// Look for UserSecretsId in any PropertyGroup
return _projectXml
.Descendants("PropertyGroup")
.Elements("UserSecretsId")
.FirstOrDefault();
}
}
📌 Usage Example
class Program
{
static void Main()
{
var reader = new CsProjSecretsReader(@"C:\Projects\MyApp\MyApp.csproj");
if (reader.Exists())
{
Console.WriteLine("UserSecretsId found:");
Console.WriteLine(reader.GetValue());
}
else
{
Console.WriteLine("UserSecretsId not found.");
}
}
}
🛠 Notes
This assumes the .csproj file is well-formed XML.
You can expand this to validate GUID format or handle multiple sections if needed.
XDocument.Load throws on malformed XML—consider wrapping it with try/catch if working with unstable inputs.
Would you like a version using XmlDocument for a more traditional approach, or is LINQ to XML your preferred style?