Adding custom information to CSPROJ files

2019-06-16 08:53发布

As part of our development life cycle we have a number of process that we run against the C# source in our projects.

The processes are driven off a GUI that currently reads the *.csproj file to find the source files used within the project. This works fine.

We now have a new requirement to provide some validation processes that require a call out to a web-service. The web-service needs to be provided with some credentials that are project specific. Ideally we could enter and store these credentials within the *.csproj file but I don't see a means of extending it - is there?

We don't really want to introduce a new config. file just for these settings if we can help it. Is it possible to store information like this is the *.csproj file, if not is there any other place to put it.

thanks

3条回答
爷的心禁止访问
2楼-- · 2019-06-16 09:41

VS projects support "project extensions". These are custom data stored directly in csproj/vbproj files. You can very easily read and write them even from VS. For example, the following VS macro writes such custom setting:

Dim proj As Project = DirectCast(DTE.ActiveSolutionProjects(0), Project)
proj.Globals.VariableValue("MySettingName1") = "My value1"
proj.Globals.VariablePersists("MySettingName1") = True

The following reads it back:

proj.Globals.VariableValue("MySettingName1").ToString

And the code in csproj file looks like:

  <ProjectExtensions>
    <VisualStudio>
      <UserProperties MySettingName1="My value1" />
    </VisualStudio>
  </ProjectExtensions>

Of course, this is persisted and will not be overwritten by VS.

查看更多
【Aperson】
3楼-- · 2019-06-16 09:46

I know you dismiss it but the most obvious, and probably recommended, place is in the config file. Albeit encrypted.

One config file per project does for most cases and is not a large overhead imho.

查看更多
冷血范
4楼-- · 2019-06-16 09:50

The .csproj file is basically an MSBuild file, as such you can extend it with custom values. If you right-click on a project in Visual Studio and choose "Unload Project", the project will "grey out" and you can then right-click again and choose Edit [ProjectFileName].csproj. You can then add something similar to the following:

<PropertyGroup Label="Custom">
  <Badger>1</Badger>
</PropertyGroup>

This should be persisted when the project is modified (i.e. files added/removed) and you can retrieve the values from the file, using the method of your choice.

查看更多
登录 后发表回答