Creating a C# project programmatically

Category: c# language

Question

J Andrews on Tue, 06 Jun 2006 09:08:43


I know how to create a C# solution and implement classes and save the solution and build it etc. I am looking for a method of doing all these steps in a program. Is there a way I can create a solution/project, add source files to it, save it and build it within another program, which could be a C# program.

Something like this:

CSharpSolution mySolution = new VisualStudio.CSharpSolution();
mySolution.CreateProject("myCSharpProj");
mySolution.Project.Addfiles("file1.cs");
mySolution.Save();
mySolution.Build();

Any help is appreciated.
Thanks,
J

Replies

Craig Skibo on Thu, 08 Jun 2006 00:43:38


Visual Studio is programmable, we have an automation model for Add-ins and Macros, wizard support, etc. You can start off by getting a reference to the DTE object, creating the Solution object [DTE.Solution.Create(...)], add a base project template to the solution [Solution.AddFromTemplate(...)], add items to the project [Project.AddFromFile(...)], then build the project [DTE.Solution.SolutionBuild.Build].

Craig

J Andrews on Thu, 08 Jun 2006 03:50:57


Thanks for the reply. I will try it out and see how it works.

Thanks,
J

J Andrews on Thu, 08 Jun 2006 10:11:36


Craig, thanks for the reply. I tried to follow the steps indicated by you. I am getting a COM exception when I try to execute my code.

Here is my code:
            DTE mydte = new DTE();
            mydte.Solution.Create(@"D:\TestProj", "mySoln");
            Project myProj = mydte.Solution.AddFromFile("myProj.csproj", false);
            myProj.ProjectItems.AddFromFile("Program.cs");
            myProj.Save("myProj.csproj");

I get an exception at the very first line (new DTE() ). I looked for a sample code which could help me, but couldn't find one. Can you please point me to a sample code or an article from which I can gather what's happening?

Thanks,
J

Yash Vohra on Tue, 16 Oct 2012 06:23:33


Hi

The exception you are getting is because dte object can not be created directly from constructor.

You can obtain dte object refernce like this

EnvDTE.DTE dte; DTE = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.7.1")

for further reference see here-

http://msdn.microsoft.com/en-us/library/t6d9sf9k(v=vs.71).aspx