I have got this code which should read path from app.Settings
but now I have value there and when I release this project as .exe
file and I try to install it on another computer after successful instalation I run it and it throws an error with system.IO.directorynotfound
.
I thought that it can look something like this:
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();
}
But it gives following error: The name 'cb' does not exist in the current context
- yes I know why because it is not inside the arrange of If. But Im not sure how to improve it so if the path wasn't found on particular computer the program will normally continue until I set the right path.
Thank you everyone for your time and answers.
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:
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)