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

3

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 can help it. Due to the logging on source control.

visual-studio
visual-studio-2010
add-in
envdte
asked on Stack Overflow Mar 31, 2011 by STEVEN PARRY • edited Nov 28, 2014 by Kiquenet

2 Answers

6
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.

answered on Stack Overflow Oct 28, 2011 by Jeff Reinhardt
3

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);   
    }
}
answered on Stack Overflow Mar 31, 2011 by STEVEN PARRY

User contributions licensed under CC BY-SA 3.0