要从 Visual Studio 扩展 (ToolWindowPane) 创建新文件,首先使用 GetService 方法:
// Get an instance of the currently running Visual Studio IDE
DTE dte = (DTE)GetService(typeof(DTE));
其次,确保当前打开了解决方案,如果没有打开解决方案,则文件生成将不起作用:
string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);
第三,从 DTE 对象生成新文件:
dte.ItemOperations.NewFile(@"General\Visual C# Class", "ObjectOne", EnvDTE.Constants.vsViewKindTextView);
创建新文件后,使用以下代码访问该文件的文本并将其替换为您生成的文本:
TextSelection txtSel = (TextSelection)dte.ActiveDocument.Selection;
TextDocument txtDoc = (TextDocument)dte.ActiveDocument.Object("");
txtSel.SelectAll();
txtSel.Delete();
txtSel.Insert("Hello World");