C# 如何从 WPF 应用程序中的相对路径加载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/806098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load from relative path in WPF application?
提问by Edward Tanguay
I'm reading an xml file and want to make it from a relative directory based on the location of the application, similar to ASP.NET with Server.MapPath or using the tilda.
我正在读取一个 xml 文件,并希望根据应用程序的位置从相对目录中创建它,类似于带有 Server.MapPath 的 ASP.NET 或使用 tilda。
How can you get the relative path in WPF?
如何获得WPF中的相对路径?
WORKS: XDocument xmlDoc = XDocument.Load(@"c:\testdata\customers.xml");
DOES NOT WORK: XDocument xmlDoc = XDocument.Load(@"~\Data\customers.xml");
DOES NOT WORK: XDocument xmlDoc = XDocument.Load(@"~/Data/customers.xml");
采纳答案by Kent Boogaart
XDocument xmlDoc = XDocument.Load(@"Data\customers.xml");
OR
或者
XDocument xmlDoc = XDocument.Load(@".\Data\customers.xml");
BTW, this has nothing to do with WPF and everything to do with Windows paths.
顺便说一句,这与 WPF 无关,而与 Windows 路径无关。
回答by Tim Robinson
XDocument xmlDoc = XDocument.Load(
Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
@"Data\customers.xml"));
I assume the Data
directory is going to get deployed with your app, in the same root directory as your EXE. This is generally safe, except where shadow copying is involved; for example, when you use NUnit to test this code. (With shadow copying, the assemblies that make up your app get copied to a temporary directory, but files like this get left behind.)
我假设该Data
目录将与您的应用程序一起部署在与您的 EXE 相同的根目录中。这通常是安全的,除非涉及卷影复制;例如,当您使用 NUnit 测试此代码时。(通过影子复制,构成应用程序的程序集会被复制到一个临时目录,但这样的文件会被留下。)
Assuming you're not planning to modify customers.xml
after deployment, the safest way to handle this is to embed the file as a resource within your assembly.
假设您不打算customers.xml
在部署后进行修改,最安全的处理方法是将文件作为资源嵌入到程序集中。
回答by Ahm
Try File.Create("./HiImHere.txt")
to see where is the point directory; after that try the path relative to where HiImHere.txt
is.
试试看File.Create("./HiImHere.txt")
点目录在哪里;之后尝试相对于 where 的路径HiImHere.txt
。