2

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

谢谢大家的时间和答案。

4

1 回答 1

1

You have the cb.ToString outside the closing braces where is defined.

   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
   }

Beware that the function requires a return of type string. So if your path is null, you need to supply an alternative return value. And handle that possibility in the calling code.....

Usually the connectionstring is a basic piece of configuration for every database application, so, if it is not configured correctly you have only two possibilities:

  • Terminate your application with a warning to the user and ask for support assistance
  • Show a dialog box where your user inserts the needed informations.

The second approach requires a bit of knowledge from your users, so I think that in this situation (lacking of configuration settings) your best option is to terminate the application with an informative message (name and path of file and reasons to end the app)

于 2013-08-14T12:34:15.697 回答