1

有没有办法在应用设置完成后提示用户设置一次路径?

我在 C#.NET 中完成了一个项目,其中我的数据库文件是 Excel 工作簿。由于连接字符串的位置在我的编码中是硬编码的,因此在我的系统中安装它没有问题。当涉及到其他系统时,位置将不匹配.. 有没有办法在设置后初始设置路径,以便所有用户可以在不同系统中使用它?

4

3 回答 3

0

只需在程序开始时询问即可。如果用户提供了一个值或选择了“默认”,那么设置一个注册表或临时文件或其他一些标志,并在下次需要询问时使用它来提醒自己。

using System.IO;
.
.
... Main...

if(!File.Exists("user_has_toldme_already")){
   ... ask the user
   File.WriteAllText("user_has_toldme_already","dummy text");
   .
   . Set the value of my connectionstring (you could even record  it in the file above
   . and load it when you need it
}

.
. rest of code
.
于 2012-10-23T05:09:21.673 回答
0

您需要将配置文件添加到您的项目中。

Codelicious解释了如何做到这一点。

  • 添加一个 app.config 文件
  • 向该文件添加一些设置,例如

    <appSettings>
        <add key="OperatorName" value="Rita"></add>
        <add key="LoggerLevel" value="5"></add>
    </appSettings>
    
  • 使用类访问设置ConfigurationManager

该站点 - ConnectionStrings.com - 解释了如何为连接字符串执行此操作。选择最适合您的。

于 2012-10-23T05:29:44.630 回答
0

我建议将您的 ConnectionString 存储在 App.config 文件中。如下所示:

<connectionStrings>
    <clear />
     <add name="DefaultUniqueName" connectionString="Connection String"
      providerName="Provider Name" />
     <add name="UserDefine" connectionString="Connection String"
      providerName="Provider Name" />
  </connectionStrings>

在启动项目时要求用户选择连接字符串选项:1)默认或 2)选择新文件

如果用户选择新文件,则更新 UserDefine 连接字符串。

更新连接字符串 (VB.NET)

Dim oAppConfig = Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location)

oAppConfig.ConnectionStrings.ConnectionStrings("UserDefine").ConnectionString = "FilePath"
 oAppConfig.Save(Configuration.ConfigurationSaveMode.Minimal)

C#

System.Configuration.Configuration oAppConfig = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);

oAppConfig.ConnectionStrings.ConnectionStrings("UserDefine").ConnectionString = "FilePath";
oAppConfig.Save(System.Configuration.ConfigurationSaveMode.Minimal);
于 2012-10-23T05:59:54.517 回答