C#相对路径不是从工作目录开始 [英] C# relative path not start from working directory
问题描述
我有一个C#程序,它将从相对路径./report/report1.rdlc
读取文件,但是有时由于未知原因,它从完全不同的位置找到了文件C:\Windows\system32\report\report1.rdlc
,但是文件实际上位于C:\Program Files (x86)\Application1\report\report1.rdlc
并且程序在C:\Program Files (x86)\Application1\
内部.出于任何原因,相对路径不是从工作目录开始的?
I have a C# program, it will read a file from a relative path ./report/report1.rdlc
, however sometime for a unknown reason it found the file from a completely different place C:\Windows\system32\report\report1.rdlc
but the file actually is place in C:\Program Files (x86)\Application1\report\report1.rdlc
and the program is inside C:\Program Files (x86)\Application1\
. Any reason the relative path not start from working directory?
推荐答案
它确实从工作目录开始.但是,您不应使用工作目录,因为如果执行特定的IO任务(例如,有时打开文件对话框或(显然)是Directory.SetCurrentDirectory
方法),工作目录可能会有所不同.相反,您应该使用AppDomain.CurrentDomain.BaseDirectory
属性来获取程序集文件所在的路径.您可以这样使用:
It does start from the working directory. However, you shouldn't use the working directory, as it can vary if specific IO-Tasks (e.g. sometimes an Open File Dialog or (obviously) the Directory.SetCurrentDirectory
method) are performed. Instead you should use the AppDomain.CurrentDomain.BaseDirectory
property to get the path where the assembly file is located. You can use this like that:
var relativePath = Path.Combine ("report", "report1.rdlc");
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var absolutePath = Path.Combine (baseDirectory, absolutePath);
现在,您应该使用absolutePath
来访问文件.
Now you should work with the absolutePath
to access the file.
这篇关于C#相对路径不是从工作目录开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!