从Visual Studio扩展生成代码

Joh*_*ney 9 c# visual-studio-2010 office-addins visual-studio-extensions

我有一个项目,基于元数据生成文本(表示一个接口和一个类).我想采用这个生成的代码并将其作为新类和接口直接插入到特定项目和目录下当前打开的解决方案中.我将创建将生成类的菜单工具,但我不知道该怎么做是从我的自定义Visual Studio扩展中获取对以下项的访问:

  1. 迭代当前的解决方案并找到一个项目来将生成的代码转储到其中.
  2. 在Visual Studio中打开一个新文件窗口,将生成的文本从我的工具直接注入该窗口.
  3. 在我的自定义扩展中,在当前解决方案中的特定项目中创建一个新文件夹.

编辑 - 澄清我需要打开一个新文件(例如右键单击一个项目 - >添加 - >新类)并从我的自定义Visual Studio扩展中插入文本.

谢谢

Joh*_*ney 12

要从Visual Studio扩展(ToolWindowPane)创建新文件,请首先使用GetService方法:

// Get an instance of the currently running Visual Studio IDE
DTE dte = (DTE)GetService(typeof(DTE));
Run Code Online (Sandbox Code Playgroud)

其次,确保解决方案当前处于打开状态,如果没有打开解决方案,则文件生成将无效:

string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);
Run Code Online (Sandbox Code Playgroud)

第三,从DTE对象生成新文件:

dte.ItemOperations.NewFile(@"General\Visual C# Class", "ObjectOne", EnvDTE.Constants.vsViewKindTextView);
Run Code Online (Sandbox Code Playgroud)

创建新文件后,使用以下代码访问该文件的文本,并将其替换为生成的文本:

TextSelection txtSel = (TextSelection)dte.ActiveDocument.Selection;
TextDocument txtDoc = (TextDocument)dte.ActiveDocument.Object("");

txtSel.SelectAll();
txtSel.Delete();
txtSel.Insert("Hello World");
Run Code Online (Sandbox Code Playgroud)

  • 如何在不提示保存对话框(静默保存)的情况下保存生成的文件并作为项目添加到解决方案中? (2认同)