问题
I wanted to programmatically add and remove projects, solution folders and other items such as resource files to a solution, but I'm not exactly sure what would be the best way to go with that.
For those that don't know, highly simplified; this is how a sulution file (.sln) normally looks like:
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "project name", "projectpath\name.csproj", "{785ECC80-AF1B-4FBC-B97B-2EC43B7E81E8}"
EndProject
Global
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{785ECC80-AF1B-4FBC-B97B-2EC43B7E81E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
EndGlobalSection
EndGlobal
I'm not sure if this is an actual open standard such as xml (it is?), but it kind of seems like the visual basic team made its own version of xml. (not a compliment)
So anyway, what would be the best way to serialize and deserialize this to and from objects? I was thinking about making my own IFormatter, but that seems rather complex.
回答1:
Using EnvDTE library:
According to MSDN EnvDTE is an assembly-wrapped COM library containing the objects and members for Visual Studio core automation. You can also find there documentation of Solution and Project interfaces with using examples which should be very helpful.
Without EnvDTE library:
Solution file:
It seems there isn't a lot to do here - adding a project and setting build configuration. In my opinion the best approach would be to parse it using simple TextReader and rewrite it after adding some data. This is the template.
Project("{solution guid}") = "project name", "projectpath\name.csproj", "{project guid}"
Remember to use the same solution guid in every project.
Project files:
No surprises here, it is standard XML file which you can create/modify using LINQ to XML. Whole specification with examples is available here: http://msdn.microsoft.com/en-us/library/dd393574.aspx. Of course Don't forget to use the same project guid like in solution file.
I hope it will help.
回答2:
Here is some code:
using EnvDTE;
.....
Solution s = new SolutionClass();
s.Open(solutionFilePath);
s.AddFromFile(projectFilePath);
s.Remove(s.Projects[6]);
You can navigate projects as in foreach(var project in s.Projects) and check their project.Name property to find the one you want.
Add to references following dll (AddReference->Browse tab):
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\EnvDTE.dll.
All classes are pretty well documented in MSDN. EnvDTE is very powerful library for VS autoamtion, you can do much more then add/remove. I would not bother serializing sln file myself, I agree it was bad to invent own formating.
来源:https://stackoverflow.com/questions/8064675/serialize-and-deserialize-visual-studio-solution-files-or-programmatically-edi