我有这段代码,它应该从 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/