A tool for formatting .csproj files

685 Views Asked by At

Is there an option in Visual Studio or a tool (a plugin for VS?) to automatically format .csproj files if they get messed up after eg. a merge conflict resolution? Preferably format them the same way as Visual Studio does when it creates them. Maybe there is an option for that in ReSharper that I don't know about?

I have tried the command-line tool organize-csproj but it has a range of inconveniences - requires .NET Core 3.1 runtime installed, adds comments to the output .csproj, adds an XML declaration at the top and does not insert extra line breaks after each main element (after PropertyGroup or ItemGroup) like VS does. Its configuration doesn't seem to let me change that behavior either.

2

There are 2 best solutions below

5
PMF On

You can specifiy formatting options (e.g. identation) as for other files in the .editorconfig file. VS will normaly obey those rules. E.g., I have

[*.{csproj}]
charset = utf-8-bom
indent_style = space
indent_size = 2
tab_width = 2

(as opposed to .cs files, where indent_size is typically 4)

1
Axel Kemper On

You can beautify any XML file on XML level with the following method:

static void XmlFormat(string inFileName, string outFileName, 
                    bool _NewLineOnAttributes, 
                    string _IndentChars, 
                    bool _OmitXmlDeclaration)
{
    try
    {  
        //  adjust Encoding, if necessary
        TextReader rd = new StreamReader(inFileName, Encoding.Default);

        XmlDocument doc = new XmlDocument();
        doc.Load(rd);

        if (rd != Console.In)
        {
            rd.Close();
        }

        //  adjust Encoding if necessary
        var wr = new StreamWriter(outFileName, false, Encoding.Default);

        //  https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmlwritersettings?view=net-5.0
        var settings =
            new XmlWriterSettings 
            { 
                Indent = true, 
                IndentChars = _IndentChars,
                NewLineOnAttributes = _NewLineOnAttributes,
                OmitXmlDeclaration = _OmitXmlDeclaration
            };

        using (var writer = XmlWriter.Create(wr, settings))
        {
            doc.WriteContentTo(writer);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error formatting {inFileName}: {ex.Message}");
    }
}