【问题标题】:Where should I put configuration files in .NET?我应该将配置文件放在 .NET 中的什么位置?
【发布时间】:2010-12-04 19:45:24
【问题描述】:

在 .NET 中,我应该如何访问用于保存特定于当前机器或用户的配置数据的文件夹(以避免硬编码路径)?

(相关:)Which is the best location to keep program configuration file in WINDOWS?

问题已回答...顺便说一下,这是典型的 WinXP 输出

foreach (Environment.SpecialFolder f in 
         Enum.GetValues(typeof(Environment.SpecialFolder)))
    Debug.WriteLine(string.Format("{0,16}: {1}", 
                    f.ToString(), Environment.GetFolderPath(f)));
桌面:C:\Documents and Settings\user\Desktop 程序:C:\Documents and Settings\user\Start Menu\Programs 个人:C:\Documents and Settings\user\My Documents 个人:C:\Documents and Settings\user\My Documents 收藏夹:C:\Documents and Settings\user\Favorites 启动:C:\Documents and Settings\user\Start Menu\Programs\Startup 最近:C:\Documents and Settings\user\Recent SendTo: C:\Documents and Settings\user\SendTo 开始菜单:C:\Documents and Settings\user\开始菜单 我的音乐:C:\文档和设置\用户\我的文档\我的音乐 桌面目录:C:\Documents and Settings\user\Desktop 我的电脑: 模板:C:\Documents and Settings\user\Templates 应用程序数据:C:\文档和设置\用户\应用程序数据 LocalApplicationData:C:\Documents and Settings\user\Local Settings\Application Data InternetCache:C:\Documents and Settings\user\Local Settings\Temporary Internet Files Cookies:C:\Documents and Settings\user\Cookies 历史记录:C:\Documents and Settings\user\Local Settings\History CommonApplicationData:C:\Documents and Settings\All Users.WINDOWS\Application Data 系统:C:\WINDOWS\system32 程序文件:C:\程序文件 我的图片:C:\文档和设置\用户\我的文档\我的图片 CommonProgramFiles:C:\Program Files\Common Files

【问题讨论】:

    标签: .net windows directory


    【解决方案1】:

    您可以使用 Environment.GetFolderPath() 获取系统上特殊文件夹的路径,无论它们的位置如何,包括要保存的配置文件夹和文件的标准位置:

    // Returns the user specific config folder
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    // Returns the computer specific config folder
    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
    

    然后您可以将字符串附加到您的特定应用程序文件夹并将您的数据保存在那里。

    【讨论】:

    • 这是一个很好的例子。尤其是在您可能正在部署 ClickOnce 应用程序的情况下。
    【解决方案2】:

    除了必须在应用程序文件夹中的 App.config 之外,您可以将它们放在任何地方。但是,我建议您在应用程序文件夹下为所有必需的应用程序文件建立一个逻辑组织的文件夹结构,并且所有配置文件的“config”文件夹当然是好的开始。

    请记住,如果配置文件 在应用程序文件夹中,则必须在 app.config 中放置一个重定向行来告诉配置子系统在哪里找到它...

     <appSettings configSource="Config\AppSettings.config" />
    

    【讨论】:

    • 应用文件夹下?我听说 Program Files 在 Vista 上是只读的。
    【解决方案3】:
    string path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
    

    Look here for all possible values of SpecialFolder

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-26
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      相关资源
      最近更新 更多