开发者

How do I Edit a .cs file in a Add-In Project using DTE

I'm trying to write my first add-in for vs2010, but im struggling.

I have a assembly that generates lots of cs files. I want my plugin to add new files to the select project or if the files exist, overwrite them.

I'm having 2 problems:

  1. When I add a new file, how do I add it to a sub folder inside the project? I seem to only be able to add to the root of the project.
  2. If a cs file exists, how do I clear its content? Im using the EnvDTE.TextDocument & EnvDTE.EditPoint interfaces. But every time I try and iterate through the document clearing lines, I get a COM error "Exception from HRESULT: 0x80041001".

    I dont want to delete the file and add a new file if I ca开发者_运维技巧n help it. Due to the logging on source control.


textDoc = (TextDocument) document.Object("TextDocument");
EditPoint editPoint = (EditPoint)textDoc.StartPoint.CreateEditPoint();
EditPoint endPoint = (EditPoint)textDoc.EndPoint.CreateEditPoint();
editPoint.Delete(endPoint);

No looping needed and your editpoint never moves from the first position.


Well i've got a one way of doing this working.

 
// Get an instance of the currently running Visual Studio IDE.
var dte2 = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0");

//I store the list of projects in dte2.Solution.Projects in a combobox

EnvDTE.Project project = (EnvDTE.Project)projectList.SelectedValue; //I get my projects out of a combobox

foreach (ProjectItem projectItem in project.ProjectItems)
{
    Document document;
    try
    {
        projectItem.Open();
        document = projectItem.Document;
    }
    catch(Exception)
    {
        Console.WriteLine("failed to load document");
        continue;
    }
    if (document == null)
    {
        continue;
    } 

    if (document.Name == "Class1.cs") //whatever file your after
    {
        TextDocument editDoc = (TextDocument) document.Object("TextDocument");
        EditPoint objEditPt = editDoc.CreateEditPoint();
        objEditPt.StartOfDocument();
        document.ReadOnly = false;

        while (!objEditPt.AtEndOfDocument)
        {           
            objEditPt.Delete(objEditPt.LineLength); 
            objEditPt.LineDown(1);
        }

        objEditPt.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsHorizontal);
        objEditPt.DeleteWhitespace(vsWhitespaceOptions.vsWhitespaceOptionsVertical);

        Console.WriteLine("saving file {0}", document.FullName);
        document.Save(document.FullName);   
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜