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

前端 未结 6 2662
清歌不尽
清歌不尽 2021-02-19 18:44

An app I use interprets a .NET .config file. I added a line specifying the path to a certificate it needs



        
相关标签:
6条回答
  • 2021-02-19 18:53

    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);
                }
    
    0 讨论(0)
  • 2021-02-19 18:54

    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

    0 讨论(0)
  • 2021-02-19 18:55

    By using the tilde

    value="~/certificate.abc"
    
    0 讨论(0)
  • 2021-02-19 19:00

    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]") '
    
    0 讨论(0)
  • 2021-02-19 19:02

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

    0 讨论(0)
  • 2021-02-19 19:18

    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.

    0 讨论(0)
提交回复
热议问题