在设计时获取文件的相对路径 [英] Get relative path to file at design time

查看:42
本文介绍了在设计时获取文件的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 Windows 手机 8 应用.

I am building a Windows phone 8 app.

在设计时,我加载了一个示例 XML 文件以获取示例数据.它运行良好,但我想使用相对于解决方案根目录的文件路径,以便它适用于所有具有相同代码的开发人员.

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.

这是我当前的代码:

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

我尝试了像@"SampleData\stub.xml" 这样的相对路径.它适用于手机,但在设计时出现此错误:

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

DirectoryNotFoundException: 找不到路径C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\SampleData\login.xml"的一部分.

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

推荐答案

这是我所做的:

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

这篇关于在设计时获取文件的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆