我有这个代码应该读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的排列中。但我不知道如何改进它,所以如果在特定计算机上找不到路径,程序通常会继续,直到我设置正确的路径。
感谢大家的时间和答案。
答案 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是每个数据库应用程序的基本配置,因此,如果配置不正确,您只有两种可能:
第二种方法需要用户的一些知识,因此我认为在这种情况下(缺少配置设置),您最好的选择是使用信息性消息终止应用程序(文件的名称和路径以及结束的理由)应用程序)