C# to format (indent, align) C# properly

前端 未结 6 1912
心在旅途
心在旅途 2021-01-02 16:17

We have a code generator that munges the schema of a given database to automate our inhouse n-tier architecture. The output is various C# partial classes, one per file.

6条回答
  •  半阙折子戏
    2021-01-02 16:47

    Here's how to do it from the context of a macro or add-in:

    var dte = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.8.0");
    dte.ExecuteCommand("File.OpenFile", filename);
    dte.ExecuteCommand("Edit.FormatDocument", filename);
    dte.ActiveDocument.Close(vsSaveChanges.vsSaveChangesYes);
    

    Warning: As @Greg Hurlman says, the output will vary depending on the user's current options.

    Edit:

    unfortunately your method requires me to have an instance of VS running alongside my winforms app. Can you think of a way to create an instance of VS from within my app (if that's even possible)?

    I think it might be possible to do from within your Win.Form app. However, you'll have to have Visual Studio installed on the machine running the code.

    Try this:

    var dte = (EnvDTE80.DTE2)Microsoft.VisualBasic.Interaction.CreateObject("VisualStudio.DTE.8.0", "");
    dte.ExecuteCommand("File.OpenFile", filename);
    dte.ExecuteCommand("Edit.FormatDocument", filename);
    dte.ActiveDocument.Close(vsSaveChanges.vsSaveChangesYes);
    

    Keep in mind that you'll need references to the EnvDTE80.dll assembly.

提交回复
热议问题