How do you get the solution directory in C# (VS 2008) in code?

后端 未结 6 2364
时光取名叫无心
时光取名叫无心 2020-12-10 05:29

Got an annoying problem here. I\'ve got an NHibernate/Forms application I\'m working through SVN. I made some of my own controls, but when I drag and drop those (or view som

6条回答
  •  猫巷女王i
    2020-12-10 06:01

    I've finally figured this one out. This will work for any Visual Studio version, does not rely on EnvDTE, and solves the original problem presented here.

    1. In your project settings, under "Build Events", add the following "Pre-build event command line":

      echo $(SolutionDir) > ..\..\solutionpath.txt
      
    2. Build the project once. The file will be created in your project root.

    3. In solution explorer, click "Show All Files" and "Refresh"

    4. Add solutionpath.txt to your solution

    5. Right click solutionpath.txt, click properties. Change your build action to "Embedded Resource"

    6. Use the following code to get your solution path.

          string assemblyname = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
          string path = "";
          using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(assemblyname + ".solutionpath.txt"))
          {
              using (var sr = new StreamReader(stream))
              {
                  path = sr.ReadToEnd().Trim();
              }
          }
      

    Because this is a pre-build event, the file does not need to exist before the build is started, so it is compatible with source-control and doesn't have any obvious issues.

提交回复
热议问题