C# relative path not start from working directory

自作多情 提交于 2019-12-01 22:45:46

问题


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?


回答1:


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);

Now you should work with the absolutePath to access the file.



来源:https://stackoverflow.com/questions/43510243/c-sharp-relative-path-not-start-from-working-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!