2009-05-15 4 views
4

.NET 3.5 및 Visual Studio 2008 Express를 사용하는 C# 응용 프로그램에서 일부 설정을 만들었습니다. 응용 프로그램 범위 내에서 수정할 수있는 여러 가지 응용 프로그램 범위 설정이 있습니다. Properties.Settings.Default을 통해 액세스 할 수 있지만 예상대로 읽기만 가능합니다. 나는 이것이 애플 리케이션 차원에서 이루어져야하므로 사용자 범위 설정이되도록하고 싶지 않습니다. XML을로드하고 읽거나 쓰지 않고이 작업을 수행 할 수 있습니까?[appname] .exe.config를 수동으로 XMl을 읽거나 쓸 필요없이 수정할 수 있습니까?

나는 System.Configuration.ConfigurationManager.OpenExeConfiguration를 사용하는 예를 본 적이 있지만, 구성 XML은 내가 사용하고있는 것과 다른 형식으로 보인다 (이전 버전에서이 있나요?)

감사


을 편집

저는이 작업을 수행하는 값을 수정할 수는 있지만 효과가 없다고 생각합니다.

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 
SettingElementCollection settingElements = ((ClientSettingsSection)config.GetSectionGroup("applicationSettings").Sections[0]).Settings; 

SettingElement element = settingElements.Get("SettingName"); 
element.Value.ValueXml.InnerText = "new value"; 

config.Save(ConfigurationSaveMode.Modified, true); 

답변

1

OpenExeConfiguration (또는 다른 임의의 방법 ConfigurationManager)는 대부분의 변형이 파일을 구성하기위한 바람직한 엔트리 포인트이다. Configuration 인스턴스가 있으면 수정하려는 섹션을 얻고 수정 후에 ConfigurationManager.Save 메서드 중 하나를 호출해야합니다. 그러나이 방법으로 applicationSettings 섹션을 검색하는 것은 불가능합니다.

app.config 파일의 applicationSettings 섹션에서 설정을 변경하는 API가 없습니다. 이 방법으로 사용자 범위 설정 만 변경할 수 있습니다.

실제로 이러한 설정을 변경하는 것은 app.config XML 파일을 직접 조작해야 수행 할 수 있습니다.

인덱스 된 속성 Properties.Settings.Default이 실제로 쓰기 가능하기 때문에 약간의 혼동이 발생할 수 있습니다. 다음은 완전히 합법적입니다.

Properties.Settings.Default["MySetting"] = "New setting value"; 
Properties.Settings.Default.Save(); 

그러나 설정은 저장되지 않습니다.

+0

그리고 구성 파일에 대한 사용 권한을 허용해야합니다. App.exe.config는 관리자에게만 쓸 수 있어야합니다. – Richard

+0

감사합니다.Properties.Settings.Default에서 설정을 가져 오려면 어떤 섹션이 필요합니까? –

+0

나는 당신의 질문을 충분히 읽지 못했다. 필자가 제안하는 방법은 구성 파일을 일반적으로 변경하는 것입니다. 어셈블리 범위 설정을 변경하는 또 다른 (더 나은) 방법을 보여주기 위해 내 대답을 업데이트했습니다. –

1

Windows 레지스트리를 사용하여 응용 프로그램 별 상태를 저장할 수도 있습니다. 레지스트리에는 사용자 별 및 컴퓨터 별 키가 있으며 두 키 중 하나 또는 두 키를 사용할 수 있습니다. 예를 들어 일부 사용자는 레지스트리를 사용하여 이탈시 앱 창의 위치와 크기를 저장합니다. 그런 다음 앱을 다시 시작하면 마지막으로 알려진 크기에 따라 창을 배치하고 크기를 지정할 수 있습니다. 이것은 레지스트리에 저장할 수있는 상태의 작은 예제입니다.

이렇게하려면 저장 및 검색을 위해 다른 API를 사용하십시오. 특히 SetValue 및 GetValue는 Microsoft.Win32.RegistryKey 클래스를 호출합니다. 복잡한 상태를 레지스트리에 유지하는 데 유용한 라이브러리가있을 수 있습니다. 간단한 경우 (몇 개의 문자열과 숫자)라면 쉽게 할 수 있습니다.

private static string _AppRegyPath = "Software\\Vendor Name\\Application Name"; 

    public Microsoft.Win32.RegistryKey AppCuKey 
    { 
     get 
     { 
      if (_appCuKey == null) 
      { 
       _appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(_AppRegyPath, true); 
       if (_appCuKey == null) 
        _appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(_AppRegyPath); 
      } 
      return _appCuKey; 
     } 
     set { _appCuKey = null; } 
    } 


    private void RetrieveAndApplyState() 
    { 
     string s = (string)AppCuKey.GetValue("textbox1Value"); 
     if (s != null) this.textbox1.Text = s; 

     s = (string)AppCuKey.GetValue("Geometry"); 
     if (!String.IsNullOrEmpty(s)) 
     { 
      int[] p = Array.ConvertAll<string, int>(s.Split(','), 
          new Converter<string, int>((t) => { return Int32.Parse(t); })); 
      if (p != null && p.Length == 4) 
      { 
       this.Bounds = ConstrainToScreen(new System.Drawing.Rectangle(p[0], p[1], p[2], p[3])); 
      } 
     } 
    } 

    private void SaveStateToRegistry() 
    { 
     AppCuKey.SetValue("textbox1Value", this.textbox1.Text); 

     int w = this.Bounds.Width; 
     int h = this.Bounds.Height; 
     int left = this.Location.X; 
     int top = this.Location.Y; 

     AppCuKey.SetValue("Geometry", String.Format("{0},{1},{2},{3}", left, top, w, h); 
    } 


    private System.Drawing.Rectangle ConstrainToScreen(System.Drawing.Rectangle bounds) 
    { 
     Screen screen = Screen.FromRectangle(bounds); 
     System.Drawing.Rectangle workingArea = screen.WorkingArea; 
     int width = Math.Min(bounds.Width, workingArea.Width); 
     int height = Math.Min(bounds.Height, workingArea.Height); 
     // mmm....minimax    
     int left = Math.Min(workingArea.Right - width, Math.Max(bounds.Left, workingArea.Left)); 
     int top = Math.Min(workingArea.Bottom - height, Math.Max(bounds.Top, workingArea.Top)); 
     return new System.Drawing.Rectangle(left, top, width, height); 
    } 

그 코드는 Microsoft.Win32.Registry.CurrentUser를 사용하고, 그래서 설정하고 사용자 별 응용 프로그램 설정을 검색합니다. 컴퓨터 전체 상태를 설정하거나 검색하는 경우 Microsoft.Win32.Registry.LocalMachine이 필요합니다.

관련 문제