如何在不重新编译的情况下配置C#项目? [重复]

问题描述 投票:0回答:1

因此,我想使用.exe执行程序,并且我想在不实际写入代码的情况下配置程序。

我的代码中有一些是非问题,例如:您想压缩什么?文件/目录。编辑:我不想在控制台应用程序中回答这些问题,我想在“设置”之前回答这些问题。

[我的问题是,我可以不编写代码就回答这些问题,并以这种方式使该应用程序可执行吗?是否有任何程序?

感谢您的回答!

c# configuration executable
1个回答
2
投票

您有2种方法可以使用,具体取决于您的使用习惯,第一个建议是万一您正在使用程序,而不必太频繁地设置值

  1. 您可以使用app.config文件并添加相关值,并通过代码将其作为变量调用。

  2. 您可以将一个小的配置文件abd写入xml文件或json文件,并轻松对其进行编辑,这对于使用您的应用的客户来说,可以通过配置文件轻松地更改配置。

为此,请尝试使用xml序列化和反序列化对象,如果需要,我将添加代码示例。

编辑要使用外部配置,您需要以下类:1.配置数据对象

[Serializable]
public class Configuration : ICloneable
{
    public Configuration()
    {
        a = "a";
        b= "b"
    }

    public string a { get; set; }
    public string b { get; set; }

    public object Clone()
    {
        return new Configuration
        {
            a = a,
            b= b
        };
    }
}
  1. 文件读写类

    public class ConfigurationHandler
    {
     public string DefaultPath = "yourPath";
    
    public ConfigurationHandler(string path = "")
    {
        if (!File.Exists(DefaultPath))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(DefaultPath));
            FileStream file = File.Create(DefaultPath);
            file.Close();
    
            Configuration = new Configuration();
            SaveConfigurations(DefaultPath);
        }
    }
    
    public void SaveConfigurations(string configPath = "")
    {
        if (string.IsNullOrEmpty(configPath))
            configPath = DefaultPath;
        var serializer = new XmlSerializer(typeof(Configuration));
        using (TextWriter writer = new StreamWriter(configPath))
        {
            serializer.Serialize(writer, Configuration);
        }
    }
    
    
    public Configuration LoadConfigurations(string configPath = "")
    {
        if (string.IsNullOrEmpty(configPath))
            configPath = DefaultPath;
        using (Stream reader = new FileStream(configPath, FileMode.Open))
        {
            // Call the Deserialize method to restore the object's state.
            XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
            Configuration = (Configuration)serializer.Deserialize(reader);
        }
        return Configuration;
    }
    

    }

要获取配置实例,可以从程序中使用它:

 static void Main(string[] args)
    {
        var config = new ConfigurationHandler().LoadConfigurations();
        //....
     }
© www.soinside.com 2019 - 2024. All rights reserved.