autoformat code from command line

前端 未结 5 853
执念已碎
执念已碎 2020-12-14 01:59

Is it possible to run auto-format code for all or for specific file in solution, like (Ctrl+K, Ctrl+D) formatting in Visual Studio but from it`s command line? Or use Reshar

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 02:21

    As a followup to Dilshod's post, if you're just looking to format a single file, here's a way of doing it that won't need a temporary path:

    static void FormatFile(string file)
    {
        EnvDTE.Solution soln = System.Activator.CreateInstance(
            Type.GetTypeFromProgID("VisualStudio.Solution.10.0")) as EnvDTE.Solution;
    
        soln.DTE.ItemOperations.OpenFile(file);
    
        TextSelection selection = soln.DTE.ActiveDocument.Selection as TextSelection;
        selection.SelectAll();
        selection.SmartFormat();
    
        soln.DTE.ActiveDocument.Save();
    }
    

    Note that "file" will need to have the full path on disk in all likelihood. Relative paths don't seem to work (though I didn't try all that hard).

提交回复
热议问题