错误 - 在安装C#Project.exe期间添加连接字符串

时间:2014-09-26 06:40:05

标签: c# connection installation

我遵循了本教程http://www.codeproject.com/Tips/446121/Adding-connection-string-during-installation,但在安装中遇到错误

错误1001无法创建ProjectName.Installer安装程序类型的实例 - >调用的目标引发了异常 - >未将对象引用设置为对象的实例。

我的Installer.cs代码:

 public Installer()
        {
            InitializeComponent();
            string dataSource = "Data Source =" + Context.Parameters["DataSource"];
            string initialcatalog = "Initial Catalog=" + Context.Parameters["InitialCatalog"];
            string userid = "User ID=" + Context.Parameters["UserID"];
            string password = "Password=" + Context.Parameters["Password"];
            dataSource = dataSource + ";" + initialcatalog;
            dataSource = dataSource + ";Persist Security Info=True;"+userid+";"+password;
            MessageBox.Show("instance=" + dataSource);
            ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            MessageBox.Show(Assembly.GetExecutingAssembly().Location + ".config");
            //Getting the path location 
            string configFile = string.Concat(Assembly.GetExecutingAssembly().Location, ".config");
            map.ExeConfigFilename = configFile;
            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.
            OpenMappedExeConfiguration(map, System.Configuration.ConfigurationUserLevel.None);
            string connectionsection = config.ConnectionStrings.ConnectionStrings
            ["TECHNOSOFT.Properties.Settings.Tech2014ConnectionString1"].ConnectionString;

            ConnectionStringSettings connectionstring = null;
            if (connectionsection != null)
            {
                config.ConnectionStrings.ConnectionStrings.Remove("TECHNOSOFT.Properties.Settings.Tech2014ConnectionString1");
                MessageBox.Show("removing existing Connection String");
            }

            connectionstring = new ConnectionStringSettings("TECHNOSOFT.Properties.Settings.Tech2014ConnectionString1", dataSource);
            config.ConnectionStrings.ConnectionStrings.Add(connectionstring);

            config.Save(ConfigurationSaveMode.Modified, true);
            ConfigurationManager.RefreshSection("connectionStrings");
        }

我失踪了什么?帮助

1 个答案:

答案 0 :(得分:0)

Context属性在构造函数中仍为null。这就是你得到一个null异常的原因。 而是将您的逻辑移动到Install()方法。

public override void Install(IDictionary stateSaver)
{
    // Access context and put your logic here
}