开发者

How to set a universal path for the files to be read in an App.Config file

开发者 https://www.devze.com 2023-03-22 23:27 出处:网络
I 开发者_如何学编程have some text files to be read that are located in the visual studio project. My app.config file should adapt the path of these files automatically. i.e., suppose I have a file in

I 开发者_如何学编程have some text files to be read that are located in the visual studio project. My app.config file should adapt the path of these files automatically. i.e., suppose I have a file in the location C:\Visual Studio\Test Project\Read.txt, the same project when I put into D:\ drive, I should not change the path to D:\Test Project\Read.txt It should adapt the change in location automatically.


Your app.config file cannot adapt automatically. Generally, this is the task of installation or deployment scripts, to make sure that all the configuration is set up properly.

However, your program can dynamically adapt if it knows that your configuration files is storing relative paths. Instead of doing

var reader = new StreamReader(Configuration.AppSettings["fileToRead"]);

Do this (reference the file relative to the currently executing assembly):

var path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).CodeBase);
path = Path.Combine(path, Configuration.AppSettings["fileToRead"])

var reader = new StreamReader(path);
0

精彩评论

暂无评论...
验证码 换一张
取 消