Search code examples
c#wpfxamlrelative-path

Get relative path to file at design time


I am building a Windows phone 8 app.

At design time I load a sample XML file to get sample data. It works well but I want to use path to file that is relative to solution root so it can work for all developpers with the same code.

Here is my current code:

var path = @"C:\Users\Tom\MyProject\SampleData\stub.xml";
xml = new StreamReader(path).ReadToEnd();

I tried a relative path like @"SampleData\stub.xml". It works on phone but at design time I get this error:

DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\SampleData\login.xml'.


Solution

  • Here is what I did :

    var path = "SampleData/stub.xml";
    var res = Application.GetResourceStream(new Uri(path, UriKind.Relative));
    xml = new StreamReader(res.Stream).ReadToEnd();