c#在第一次运行时编写设置类应用程序作用域



我想为我的应用程序设置应用程序代码,所以我做了一个具有GUID的只读设置字段,我如何在我的应用程序首次运行时将该字段设置为随机?

我试过了:

internal sealed partial class ApplicationSettings 
{
    public ApplicationSettings() {
    //If installation code not set yet, assign a new one
    if (this.InstallationCode == System.Guid.Empty)
    {
        this["InstallationCode"] = System.Guid.NewGuid();
        this.Save();
    }
...
}

但是它不保存代码,它在每次运行时给我一个随机代码。如何做到这一点?

EDIT如果它只能在安装过程中写入,这是怎么做到的?

对application.exe.config的访问是只读的。一个原因是,因为该文件位于程序目录时受UAC保护。因此,没有管理权限就不能修改它,即使。net框架允许这样做(它不允许)。

  1. 您可以在安装过程中写入此值(如果有的话)。
  2. 另一种可能是将值存储在注册表中。但是我认为你也需要HKLM部分的管理员权限。

如果你想把它放在app.config文件中,你最好把它作为安装过程的一部分。第二种选择是尝试将文件作为常规XML文档加载,并在文档中插入GUID,然后将其保存到文件中。如果文件没有写权限,那么你必须找到另一种方式,也许作为UAC在你的应用程序。

这样做是可以的,不过您可能需要保存新创建的GUID,以便在第一次运行应用程序时使用:

    private void CreateNewGUIDIfNotExist()
    {
        string configFilePath = "myAppName.exe.config";
        var doc = new XmlDocument();
        doc.Load(configFilePath);
        var node = doc.SelectSingleNode("//appSettings");
        foreach (XmlNode settingNode in node.SelectNodes("add"))
        {
            if (settingNode.Attributes["key"].Value == "MyGUID")
            {
                var guidNode = settingNode.Attributes["value"];
                if (string.IsNullOrEmpty(guidNode.Value))
                    guidNode.Value = System.Guid.NewGuid().ToString();
                doc.Save(configFilePath);
                return;
            }
        }
    }

如果您不想在文档中创建节点,则需要像这样从一个空GUID开始:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="MyGUID" value=""/>
    </appSettings>
</configuration>

最新更新