.net에서 프로그래밍 방식으로 연결 문자열 구성을 설정하려면 어떻게해야합니까?
구성 파일 / 레지스트리 키를 전혀 변경하지 않고 프로그래밍 방식으로 연결 문자열을 설정하고 싶습니다.
이 코드가 있지만 불행히도 "구성이 읽기 전용입니다"라는 예외가 발생합니다.
ConfigurationManager.ConnectionStrings.Clear();
string connectionString = "Server=myserver;Port=8080;Database=my_db;...";
ConnectionStringSettings connectionStringSettings =
new ConnectionStringSettings("MyConnectionStringKey", connectionString);
ConfigurationManager.ConnectionStrings.Add(connectionStringSettings);
편집 : 문제는 구성에서 연결 문자열을 읽는 기존 코드가 있다는 것입니다. 따라서 구성 문자열을 수동으로 설정하거나 리소스를 통해 설정하는 것은 유효한 옵션처럼 보이지 않습니다. 내가 정말로 필요한 것은 프로그래밍 방식으로 구성을 수정하는 방법입니다.
나는 이것에 대해 내 블로그 포스트에 썼다 . 비공개 필드 (및 메서드)에 액세스하는 방법으로 리플렉션을 사용하여 값을 찌르는 것입니다.
예.
var settings = ConfigurationManager.ConnectionStrings[ 0 ];
var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );
fi.SetValue(settings, false);
settings.ConnectionString = "Data Source=Something";
사용자가 로컬 SQL Server를 선택하여 한 번의 클릭으로 응용 프로그램에서 연결 문자열을 수정할 수 있도록 허용하는 것과 동일한 질문에 대한 답을 찾고있었습니다.
아래 코드는 로컬에서 사용 가능한 모든 SQL Server에 연결하고 하나를 선택할 수있는 사용자 양식을 표시합니다. 그런 다음 해당 서버에 대한 연결 문자열을 구성하고 양식의 변수에서 반환합니다. 그런 다음 코드는 구성 파일을 수정하고이를 저장합니다.
string NewConnection = "";
// get the user to supply connection details
frmSetSQLConnection frm = new frmSetSQLConnection();
frm.ShowDialog();
if (frm.DialogResult == DialogResult.OK)
{
// here we set the users connection string for the database
// Get the application configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the connection strings section.
ConnectionStringsSection csSection = config.ConnectionStrings;
foreach (ConnectionStringSettings connection3 in csSection.ConnectionStrings)
{
// Here we check for the preset string - this could be done by item no as well
if (connection3.ConnectionString == "Data Source=SQL204\\SQL2008;Initial Catalog=Transition;Integrated Security=True")
{
// amend the details and save
connection3.ConnectionString = frm.Connection;
NewConnection = frm.Connection;
break;
}
}
config.Save(ConfigurationSaveMode.Modified);
// reload the config file so the new values are available
ConfigurationManager.RefreshSection(csSection.SectionInformation.Name);
return clsDBMaintenance.UpdateDatabase(NewConnection))
}
이에 접근하는 또 다른 방법은 컬렉션에서 직접 작업하는 것입니다.
var settings = ConfigurationManager.ConnectionStrings;
var element = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
var collection = typeof(ConfigurationElementCollection).GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
element.SetValue(settings, false);
collection.SetValue(settings, false);
settings.Add(new ConnectionStringSettings("ConnectionStringName", connectionString));
// Repeat above line as necessary
collection.SetValue(settings, true);
element.SetValue(settings, true);
이것이 저에게 효과적이라는 것을 알았습니다.
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (section != null)
{
section.ConnectionStrings["MyConnectionString"].ConnectionString = connectionString;
config.Save();
}
기존 연결 문자열을 덮어 씁니다.
I'm currently using dependency injection to handle different connection strings in dev/prod vs. test environments. I still have to manually change the webconfig if I want to move to between dev and prod, but for testing I have an IConnectionStringFactory interface with a default implementation that looks at the web config and an alternate testing configuration that returns static values. That way when I'm testing I simply set the factory to the testing implementation and it will return the testing connection string for the key I ask for. Otherwise it will look in the webconfig.
I could extend this to another implementation for dev vs. prod but I'm more comfortable having a single implementation of IConnectionStringFactory in my production assembly and the testing implementation in my testing assembly.
You could put it in a resources file instead. It won't have the built-in features of the ConfigurationManager class, but it will work.
Assuming Resources.resx:
Resources.Default.ConnectionString = "Server=myserver;" // etc
Then in your code:
conn.ConnectionString = Resources.Default.ConnectionString
It's a hack, I know.
In addition to the other answers given, and assuming the connection string is not simply another configuration variable or constant as a whole, you might consider using SqlConnectionStringBuilder class instead of directly concatenating the string together.
EDIT: Ups, sorry just saw that you basically want to read your connection string (complete I guess) from another source.
Looks like the naming was changed as of .net Core 2.1 Modifying David Gardiner's answer This way should work for referencing new and old versions:
var settings = ConfigurationManager.ConnectionStrings[ 0 ];
var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );
if(fi == null)
{
fi = typeof(System.Configuration.ConfigurationElementCollection).GetField("_readOnly", BindingFlags.Instance | BindingFlags.NonPublic);
}
fi.SetValue(settings, false);
settings.ConnectionString = "Data Source=Something";
ConfigurationManager is used to read from the config file.
Your solution is to simply set conn.ConnectionString to the conn string you need.
'developer tip' 카테고리의 다른 글
예약 된 이벤트가 아닌 람다 함수로 SQS 대기열을 처리하는 방법은 무엇입니까? (0) | 2020.12.07 |
---|---|
Vue.js-단일 파일 구성 요소에서 전역 적으로 사용 가능한 도우미 기능 만들기 (0) | 2020.12.07 |
스윙 : ESC 키를 눌렀을 때 대화 상자를 어떻게 닫습니까? (0) | 2020.12.07 |
Linux에서 인터페이스의 IP 주소 가져 오기 (0) | 2020.12.07 |
Ubuntu 9.10에서 openCV를 확인하는 방법 (0) | 2020.12.07 |