c# - IO.directorynotfound - 动态 SqlConnection 字符串

标签 c# sql sql-server io sqlconnection

我有这段代码,它应该从 app.Settings 中读取 path 但现在我在那里有值(value),当我将这个项目作为 .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();
 }

但它给出了以下错误:当前上下文中不存在名称“cb” - 是的,我知道为什么,因为它不在 If 的排列内。但我不确定如何改进它,所以如果在特定计算机上找不到路径,程序通常会继续,直到我设置正确的路径。

感谢大家的宝贵时间和回答。

最佳答案

您在定义的右大括号外有 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
   }

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

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

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

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

关于c# - IO.directorynotfound - 动态 SqlConnection 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18231844/

相关文章:

c# - 在哪里可以找到 Telegram Api key

c# - 如何将多个选项的值从选择列表发布到 MVC Controller ?

c# - 从 C# 项目中的自定义文件夹中获取文件

java - 敏感可滚动结果集不反射(reflect) Oracle 数据库中的数据库更改

php - 在 MySQL 中编写子查询是一种好习惯吗?

sql-server - 使用 Node.js 连接到 Microsoft SQL Server 2008 (MSSQL) 数据库

C#:找出哪个星期一是本月的第三个星期一?

sql - 在数据库 : relational or multidimensional? 中存储多维数组

sql-server - sql中将varchar值转换为int数据类型时转换失败

sql-server - 无需事务日志即可恢复 SQL Server 数据库