How to specify path in .config file relative to the file?

喜欢而已 提交于 2019-12-04 02:47:06

By using the tilde

value="~/certificate.abc"

In visual studio 2015, the "~" keyword has no longer worked. You can now use :

value="folder\subfoler"

"folder" has the same level with .exe file

You can't change this just by changing the config file. Unless you use an absolute path.

If you can change the application ...

If this is an asp.net application, then use Server.MapPath. If it's a Windows app, you need to get the directory of the executing application and combine that with the relative path in your config file.

System.Reflection.Assembly.GetExecutingAssembly().Location will give you the path to the .EXE file. You can then call Path.Combine to combine your relative path with the application's path.

aolisa

..\ goes up a folder level. Repeat as many times as needed e.g. ..\..\ to get to your bin folder.

I think in your case you need set file name. Folder where all files you know (if folder can be canged - set folder without ../)

And where you need use path - combine current location of application(can be got in runtime ) and key from settings

or use

System.Web.HttpContext.Current.Server.MapPath("~/[PARTH_TO_FILE]") '

you config file may lie on other location then the executing file. as you mantion executing path i understand this is the desktop based application so here you go what you can do like this.

in Config.

 <setting name="FilePath" serializeAs="String">
        <value>AppPath\MyFile.abc</value>
    </setting>

and to retrive this.

   var path = System.Configuration.ConfigurationManager.AppSettings["FilePath"];

            if  (path !=null && path.Contains("AppPath"))
            {

                var filepath = System.IO.Path.Combine(
                    System.Reflection.Assembly.GetExecutingAssembly().Location,
                    path.Replace("AppPath", string.Empty).ToString());

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