Adassko
Adassko

Reputation: 5343

Getting source directory's path while in WPF's design mode

I would like to retrieve some contents from a file that lies in source directory when user is in designmode (viewing .xaml file in designer)

My current code looks like:

#if DEBUG
            if ((bool)(System.ComponentModel.DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(System.Windows.DependencyObject)).DefaultValue)) // design mode
            {
                var f = new System.IO.StreamReader(@".\somedir\myfile.txt");
                // do something with data from that file
                f.Close();
            }
#endif

but the current directory in this case is C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE and my file is not there at all.

I've tried changing current dir by:

System.IO.Directory.SetCurrentDirectory(System.Reflection.Assembly.GetExecutingAssembly().Location);

but this leads to something like:

C:\Users\User\AppData\Local\Microsoft\VisualStudio\11.0\Designer\ShadowCache\ckauoyuj.mbg\vihlqa20.ba2

which contains only .exe and .pdb files - no files marked as Content in there

I don't want to attach this file as a resource

Upvotes: 2

Views: 2213

Answers (2)

Mark Travis
Mark Travis

Reputation: 1099

Updated answer For future readers

The answer below, although it will still work, was written for .Net 4.0 which is no longer supported by Microsoft (End of life was 2016)

Marco's answer above using the CallerFilePathAttribute is the solution I would use moving forward.

Original Answer

If you are after the folder where the source code exists, during design and run time, use

var trace = new StackTrace(true);
var frame = trace.GetFrame(0);
var sourceCodeFile = Path.GetDirectoryName(frame.GetFileName());

If you are after the bin/debug or bin/release folder at design time ...

Since the code base root folder can change from machine to machine, but the output folder for the project is the same across machines (and usually relative to the code base root), you can use the code above with

Path.Combine(sourceCodeFile, outputFolder);

where outputFolder is a string constant that has the value of the output folder on the Build tab of the project Properties window.

NOTE: Changes to code run during design time are not always picked up immediately. Sometimes you will have to

  • Recompile to project.
  • Close all design/code windows that are affected by the change.
  • Run the application
  • All the above

I hope this helps.

Upvotes: 3

Marco
Marco

Reputation: 1016

There is a much easier way, just declare a method like this:

    public static void GetCurrentSourcePath([CallerFilePath] string path = "")
    {

    }

Path will have what you are looking for.

Upvotes: 2

Related Questions