问题
An app I use interprets a .NET .config
file. I added a line specifying the path to a certificate it needs
<add key="Certificate" value="..\certificate.abc"/>
However, I found the app only works when run from the exact folder its .exe
and .config
reside. If run from another folder, it fails, because it looks for the certificate at ../
expanded relative to the working directory.
What should I write in the config file, to make sure the path is ..\certificate.abc
expanded relative to the config file rather the working directory?
I can't change the app (it's not mine), I can only change the config file.
回答1:
By using the tilde
value="~/certificate.abc"
回答2:
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
回答3:
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.
回答4:
..\
goes up a folder level. Repeat as many times as needed e.g. ..\..\
to get to your bin folder.
回答5:
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]") '
回答6:
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);
}
来源:https://stackoverflow.com/questions/16168154/how-to-specify-path-in-config-file-relative-to-the-file