2017-04-18 9 views
0

구성이 언제든지 변경 될 수 있으므로 설정 파일에 일부 기본 구성 만 저장하려고했습니다. 내 응용 프로그램 사용자는 여러 환경에서 몇 가지 사항을 관리 할 수 ​​있습니다. 각 환경에는 고유 한 구성이 있습니다 (기본적으로 네트워크 위치에 대한 경로).설정 파일에 구조체 저장

각 환경에 대해 구조체를 만들었지 만 이제는 더 많은 환경을 추가해야하므로 해당 구성을 소스 코드 외부에 저장하는 것이 좋습니다.

그럼 코드를 알려 드리겠습니다. 나는 각 환경에 설명하는 두 개의 구조체를 구축 :

public struct env_conf 
{ 
    string title; 
    string path_to_xml; 
    string path_to_sharepoint; 
    List<subfolder> subfolders; 
    //Some more strings 

    public env_conf(string title, string path_to_xml, string path_to_sharepoint ...) 
    { 
    //Constructor which is setting the variables 
    } 
} 

public struct subfolder 
{ 
    string folder; 
    bool is_standard; 

    public env_conf(string folder, bool is_standard) 
    { 
    //Constructor which is setting the variables 
    } 
} 

를 그리고 이것은 환경 CONFIGS이 설정되는 방법이다 :

var finance_conf = new env_conf("MyTitle","MyXMLPath","MySPPath", 
new List<subfolder>{new subfolder("MySubFolder",true);new subfolder("MySubFolder2",false)} 
); 

var sales_conf = new env_conf("MySalesTitle","MySalesXMLPath","MySalesSPPath", 
new List<subfolder>{new subfolder("MySalesSubFolder",true);new subfolder("MySalesSubFolder2",false)} 
); 

이 마지막 단계 -는 config-인스턴스의 정의는 이제 내부한다 설정 파일.

설정 파일에 stringstring[]을 저장하는 것은 지금까지 나에게 아무런 문제가되지 않았습니다. 하지만 지금은 그 이상입니다 ...

그 이상, 나는 Visual Studio가 없습니다. 나는 SharpDevelop와 함께 일하는데, 이것은 지금까지 아주 좋았습니다.

내 구조체를 직렬화 가능으로 표시하는 것은 도움이되지 않았습니다. 또한 수동으로 설정 유형을 MyNamespace.env_conf으로 설정하면 설정 디자이너에 표시되지 않습니다. 단 "?" 유형 필드에 나타납니다. 지금은 진행 방법을 모르겠습니다. 또한 인터넷에서 찾은 모든 정보가 도움이되지 않습니다. 도와주세요.

내 XML 설정 파일을 어떻게 편집합니까? 내 소스 코드를 어떻게 편집합니까?

인사말!

+1

왜 클래스 대신 구조체를 사용하고 있습니까? 직렬화가 잘못되었습니다. –

+0

수업 일 수도 있습니다. 맞습니다. 변수와 함수가 없기 때문에 구조체도 똑같이 할 것입니다. 직렬화가 작동하지 않는 이유를 모르겠다. 그래서 내가 묻는 것이다. – xola

+0

또한 직렬화가 작동하지 않는 이유를 알지 못합니다. * 속성을 설정하는 것 외에 다른 작업을 설명하지 않기 때문입니다. – grek40

답변

0

직렬화 가능 클래스를 생성하면 설정 파일을 직렬화 해제하여 모든 인스턴스를 설정할 수 있습니다.

예를 들어, 클래스는 같을 수 있습니다

[Serializable] 
public class EnvironmentConfig 
{ 
    public string Title { get; set; } 
    public string XmlPath { get; set; } 
    public string SharepointPath { get; set; } 
    public List<SubFolder> SubFolders { get; set; } 
    public override string ToString() 
    { 
     return $"{Title}: {XmlPath}, {SharepointPath}, {string.Join(", ", SubFolders.Select(s => s.Folder))}"; 
    } 
} 

[Serializable] 
public class SubFolder 
{ 
    public string Folder { get; set; } 
    public bool IsStandard { get; set; } 
} 

그리고 코드에서, 당신은 클래스의 인스턴스를 생성 그것은 몇 가지 값을주고, 설정 파일로 직렬화 할 수 있습니다. 나중에이 파일을 직렬화 해제하여 사용자가 변경 한 내용을로드 할 수 있습니다.

이 예에서는 기본 구성을 만들고 값을 콘솔에 표시합니다. 그런 다음 사용자에게 파일을 수정할 기회를 부여하고 새 값을 표시합니다.

// Create a default config 
var defaultEnvCfg = new EnvironmentConfig 
{ 
    Title = "USWE Environment", 
    XmlPath = @"\\server\share\xmlfiles", 
    SharepointPath = @"\\server\sites\enterpriseportal\documents", 

    SubFolders = new List<SubFolder> 
    { 
     new SubFolder { Folder = "Folder1", IsStandard = true }, 
     new SubFolder { Folder = "Folder2", IsStandard = false } 
    } 
}; 

// Display original values: 
Console.WriteLine(defaultEnvCfg.ToString()); 

// Serialize the config to a file 
var pathToEnvCfg = @"c:\public\temp\Environment.config"; 
var serializer = new XmlSerializer(defaultEnvCfg.GetType()); 

using (var writer = new XmlTextWriter(
    pathToEnvCfg, Encoding.UTF8) { Formatting = Formatting.Indented }) 
{ 
    serializer.Serialize(writer, defaultEnvCfg); 
} 

// Prompt user to change the file 
Console.Write($"Please modify the file then press [Enter] when done: {pathToEnvCfg}"); 
Console.ReadLine(); 

// Deserialize the modified file and update our object with the new settings 
using (var reader = XmlReader.Create(pathToEnvCfg)) 
{ 
    defaultEnvCfg = (EnvironmentConfig)serializer.Deserialize(reader); 
} 

// Display new values: 
Console.WriteLine(defaultEnvCfg.ToString()); 

Console.Write("\nDone!\nPress any key to exit..."); 
Console.ReadKey();