Search code examples
c#visual-studiovisual-studio-2015command-linevisual-studio-extensions

Adding a existing file to a project using visual studio command lines


I'm writing an visual studio extension and I'm creating a read me file that I want to add to the c# project. I'm running this visual studio commands

var dte = (DTE2)ServiceProvider.GetService(typeof(DTE));
var tsFile = @"C:\Users\devVictorC\Documents\Visual Studio 2017\Projects\ClassLibrary1\ClassLibrary1\Readme.txt";
dte.ExecuteCommand("File.AddExistingItem", tsFile);

but I get this exception

System.Runtime.InteropServices.COMException: 'Error HRESULT E_FAIL has been returned from a call to a COM component.'

Solution

  • If you need add file to .csproj you can try this code:

    var dte = (DTE2)ServiceProvider.GlobalProvider.GetService(typeof(DTE));
    var tsFile = filePath;
    dte.ItemOperations.AddExistingItem(tsFile);
    

    Also see MSDN documentation: ItemOperations.AddExistingItem Method