找不到IO.directory-动态SqlConnection字符串

本文关键字:SqlConnection 字符串 动态 directory- IO 找不到 | 更新日期: 2023-09-27 18:27:50

我得到了这个代码,应该读path from app.Settings,但现在我在那里有了价值,当我将这个项目作为.exe文件发布,并在成功安装后尝试将其安装在另一台计算机上时,我运行了它,它会引发system.IO.directorynotfound错误。

我以为它可以看起来像这样:

 private static string _ConnectionString;
 public static string ConnectionString {
    get {
        if (_ConnectionString == null) _ConnectionString = FunctionToDynamicallyCreateConnectionstring();
        return _ConnectionString;
    }
 }
 private static string FunctionToDynamicallyCreateConnectionstring() {

    string path = Properties.Settings.Default.swPath;
    if (path != null) {
        StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));
        SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();

        cb.DataSource = DecodeFrom64(sr.ReadLine());
        cb.InitialCatalog = DecodeFrom64(sr.ReadLine());
        cb.UserID = DecodeFrom64(sr.ReadLine());
        cb.Password = DecodeFrom64(sr.ReadLine());

    }
    return cb.ToString();
 }

但它给出了以下错误:The name 'cb' does not exist in the current context-是的,我知道为什么,因为它不在If的排列中。但我不确定如何改进它,所以如果在特定的计算机上没有找到路径,程序通常会继续,直到我设置了正确的路径。

感谢大家抽出时间回答问题。

找不到IO.directory-动态SqlConnection字符串

您拥有cb。ToString位于定义的大括号外。

   private static string FunctionToDynamicallyCreateConnectionstring()
   {
        string path = Properties.Settings.Default.swPath;
        if (path != null)
        {
            StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));
            SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();

            cb.DataSource = DecodeFrom64(sr.ReadLine());
            cb.InitialCatalog = DecodeFrom64(sr.ReadLine());
            cb.UserID = DecodeFrom64(sr.ReadLine());
            cb.Password = DecodeFrom64(sr.ReadLine());
            return cb.ToString(); 
       }
       else
            return string.Empty
   }

请注意,函数需要字符串类型的返回。因此,如果您的路径为null,则需要提供一个替代的返回值。并在调用代码中处理这种可能性。。。。。

通常,连接字符串是每个数据库应用程序的基本配置,因此,如果没有正确配置,则只有两种可能性:

  • 终止您的应用程序并向用户发出警告,并要求支持援助
  • 显示一个对话框,用户可以在其中插入所需信息

第二种方法需要用户提供一些知识,因此我认为在这种情况下(缺乏配置设置),您的最佳选择是终止应用程序,并显示一条信息性消息(文件的名称和路径以及终止应用程序的原因)