简体   繁体   中英

Determine a project's solution file location via Visual Studio Designer

We have an if statement that tries to determine where a specific folder is. Depending on whether we're running it locally (debug), or on a client's machine (release), we look for it in a different place.

#if (DEBUG)
        firefoxPath = @"..\..\..\Includes\XulRunner\";
#else
        if (System.Diagnostics.Debugger.IsAttached) {
            firefoxPath = @"..\..\..\Includes\XulRunner\";
        }
        else {
            firefoxPath = Path.Combine(Application.StartupPath, @"XulRunner\");
        }
#endif

However, when we attempt to run the designer for a project that references this one, it is unable to resolve the path, as the designer's working directory is: C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\IDE. If the path to the folder is incorrect, the project will not run correctly, and the designer crashes when it tries to load.

We can use this to determine if we are currently executing via the designer:

bool isInDesignMode = LicenseManager.UsageMode == LicenseUsageMode.Designtime || System.Diagnostics.Debugger.IsAttached == true;

My question is, how can we determine the path to the solution via the designer, so that we can correctly resolve the path to the folder that we need?

You can always get the instance of some assembly within the whole project, access the Assembly.CodeBase property and play with it:

string assemblyPath = new Uri(Assembly.GetAssembly(typeof(SomeTypeWithinYourProject)).CodeBase).AbsolutePath;

// At least you've the Bin\Debug or Bin\Release. Now you can assume some conventions
// and get project's directory. 
string binDir = Path.GetDirectoryName(binDir);

I don't know your exact case, but maybe Assembly.GetExecutingAssembly() could be enough and you don't need to load the whole assembly by giving a type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM