IO.directorynotfound - 动态SqlConnection字符串

时间:2013-08-14 12:32:13

标签: c# sql sql-server io sqlconnection

我有这个代码应该读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的排列中。但我不知道如何改进它,所以如果在特定计算机上找不到路径,程序通常会继续,直到我设置正确的路径。

感谢大家的时间和答案。

1 个答案:

答案 0 :(得分:1)

您在定义的结束括号之外有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,则需要提供替代返回值。并在调用代码中处理这种可能性.....

通常,connectionstring是每个数据库应用程序的基本配置,因此,如果配置不正确,您只有两种可能:

  • 终止您的应用程序并向用户发出警告并要求 支持援助
  • 显示用户插入所需信息的对话框。

第二种方法需要用户的一些知识,因此我认为在这种情况下(缺少配置设置),您最好的选择是使用信息性消息终止应用程序(文件的名称和路径以及结束的理由)应用程序)