SaveAs() публичный Метод

public SaveAs ( string filename ) : void
filename string
Результат void
Пример #1
0
        private OptionsForm(bool local)
        {
            InitializeComponent();
            
            // Copy the Bootstrap.exe file to New.exe,
            // so that the configuration file will load properly
            string currentDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string sandboxDir = Path.Combine(currentDir, "Sandbox");

            if (!File.Exists(Path.Combine(sandboxDir, "New.exe")))
            {
                File.Copy(
                    Path.Combine(sandboxDir, "Bootstrap.exe"),
                    Path.Combine(sandboxDir, "New.exe")
                );
            }

            string filename = local ? "New.exe" : "Bootstrap.exe";
            string filepath = Path.Combine(sandboxDir, filename);
            _Configuration = ConfigurationManager.OpenExeConfiguration(filepath);
            
            // Get the DDay.Update configuration section
            _Cfg = _Configuration.GetSection("DDay.Update") as DDayUpdateConfigurationSection;

            // Set the default setting on which application folder to use.
            cbAppFolder.SelectedIndex = 0;

            SetValuesFromConfig();

            if (!local)
                _Configuration.SaveAs(Path.Combine(sandboxDir, "New.exe.config"));
        }
Пример #2
0
    static void Main(string[] args)
    {
        try {
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            ConfigurationSection connStrings = config.ConnectionStrings;

            Console.WriteLine("connStrings[LocalSqlServer] = {0}", ((ConnectionStringsSection)connStrings).ConnectionStrings["LocalSqlServer"]);

            connStrings.SectionInformation.ProtectSection(ProtectedConfiguration.DefaultProvider);
            connStrings.SectionInformation.ForceSave = true;
            config.SaveAs("t26.exe.config", ConfigurationSaveMode.Full);

            if (connStrings.SectionInformation.IsProtected == true)
            {
                Console.WriteLine("Section {0} is now protected by {1}",
                                  connStrings.SectionInformation.Name,
                                  connStrings.SectionInformation.ProtectionProvider.Name);
            }
            else
            {
                Console.WriteLine("Section {0} is not protected", connStrings.SectionInformation.Name);
            }
        }
        catch (Exception e) {
            Console.WriteLine("{0} raised", e.GetType());
        }
    }
Пример #3
0
        private OptionsForm(bool local)
        {
            InitializeComponent();

            // Copy the Bootstrap.exe file to New.exe,
            // so that the configuration file will load properly
            string currentDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string sandboxDir = Path.Combine(currentDir, "Sandbox");

            if (!File.Exists(Path.Combine(sandboxDir, "New.exe")))
            {
                File.Copy(
                    Path.Combine(sandboxDir, "Bootstrap.exe"),
                    Path.Combine(sandboxDir, "New.exe")
                    );
            }

            string filename = local ? "New.exe" : "Bootstrap.exe";
            string filepath = Path.Combine(sandboxDir, filename);

            _Configuration = ConfigurationManager.OpenExeConfiguration(filepath);

            // Get the DDay.Update configuration section
            _Cfg = _Configuration.GetSection("DDay.Update") as DDayUpdateConfigurationSection;

            // Set the default setting on which application folder to use.
            cbAppFolder.SelectedIndex = 0;

            SetValuesFromConfig();

            if (!local)
            {
                _Configuration.SaveAs(Path.Combine(sandboxDir, "New.exe.config"));
            }
        }
Пример #4
0
        /// <summary>
        /// Altera uma chave e cria uma cópia do arquivo de Configuração da aplicação.
        /// </summary>

        /// <param name="pathDestino">Destino da cópia criada</param>
        /// <param name="nomeArquivo">Nome do arquivo</param>
        public static void CriarCopiaAppConfig(string pathDestino, string nomeArquivo)
        {
            string novoArquivo = pathDestino + "\\" + nomeArquivo + ".config";

            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.SaveAs(novoArquivo, ConfigurationSaveMode.Modified);
        }
Пример #5
0
        internal static ToolsetConfigurationSection ReadToolsetConfigurationSection(Configuration configuration)
        {
            ToolsetConfigurationSection configurationSection = null;

            // This will be null if the application config file does not have the following section 
            // definition for the msbuildToolsets section as the first child element.
            //   <configSections>
            //     <section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
            //   </configSections>";
            // Note that the application config file may or may not contain an msbuildToolsets element.
            // For example:
            // If section definition is present and section is not present, this value is not null
            // If section definition is not present and section is also not present, this value is null
            // If the section definition is not present and section is present, then this value is null
            if (null != configuration)
            {
                ConfigurationSection msbuildSection = configuration.GetSection("msbuildToolsets");
                configurationSection = msbuildSection as ToolsetConfigurationSection;

                if (configurationSection == null && msbuildSection != null) // we found msbuildToolsets but the wrong type of handler
                {
                    if (String.IsNullOrEmpty(msbuildSection.SectionInformation.Type) ||
                        msbuildSection.SectionInformation.Type.IndexOf("Microsoft.Build", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        // Set the configuration type handler to the current ToolsetConfigurationSection type
                        msbuildSection.SectionInformation.Type = typeof(ToolsetConfigurationSection).AssemblyQualifiedName;

                        try
                        {
                            // fabricate a temporary config file with the correct section handler type in it
                            string tempFileName = FileUtilities.GetTemporaryFile();

                            // Save the modified config
                            configuration.SaveAs(tempFileName + ".config");

                            // Open the configuration again, the new type for the section handler will do its stuff
                            // Note that the OpenExeConfiguraion call uses the config filename *without* the .config
                            // extension
                            configuration = ConfigurationManager.OpenExeConfiguration(tempFileName);

                            // Get the toolset information from the section using our real handler
                            configurationSection = configuration.GetSection("msbuildToolsets") as ToolsetConfigurationSection;

                            File.Delete(tempFileName + ".config");
                            File.Delete(tempFileName);
                        }
                        catch (Exception ex)
                        {
                            if (ExceptionHandling.NotExpectedException(ex))
                            {
                                throw;
                            }
                        }
                    }
                }
            }

            return configurationSection;
        }
Пример #6
0
        public void DifferentFileConfigurationSourcesDoNotShareEvents()
        {
            ConfigurationChangeWatcher.SetDefaultPollDelayInMilliseconds(50);
            string otherConfigurationFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Other.config");

            FileConfigurationSource.ResetImplementation(otherConfigurationFile, true);
            SystemConfigurationSource.ResetImplementation(true);

            File.Copy(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, otherConfigurationFile);

            try
            {
                bool sysSourceChanged   = false;
                bool otherSourceChanged = false;

                SystemConfigurationSource systemSource = new SystemConfigurationSource();
                FileConfigurationSource   otherSource  = new FileConfigurationSource(otherConfigurationFile);

                DummySection sysDummySection   = systemSource.GetSection(localSection) as DummySection;
                DummySection otherDummySection = otherSource.GetSection(localSection) as DummySection;
                Assert.IsTrue(sysDummySection != null);
                Assert.IsTrue(otherDummySection != null);

                systemSource.AddSectionChangeHandler(localSection, delegate(object o,
                                                                            ConfigurationChangedEventArgs args)
                {
                    sysSourceChanged = true;
                });

                otherSource.AddSectionChangeHandler(localSection, delegate(object o,
                                                                           ConfigurationChangedEventArgs args)
                {
                    Assert.AreEqual(12, ((DummySection)otherSource.GetSection(localSection)).Value);
                    otherSourceChanged = true;
                });

                DummySection rwSection = new DummySection();
                System.Configuration.Configuration rwConfiguration = ConfigurationManager.OpenExeConfiguration(otherConfigurationFile);
                rwConfiguration.Sections.Remove(localSection);
                rwConfiguration.Sections.Add(localSection, rwSection = new DummySection());
                rwSection.Name  = localSection;
                rwSection.Value = 12;
                rwSection.SectionInformation.ConfigSource = localSectionSource;

                rwConfiguration.SaveAs(otherConfigurationFile);

                Thread.Sleep(200);

                Assert.AreEqual(false, sysSourceChanged);
                Assert.AreEqual(true, otherSourceChanged);
            }
            finally
            {
                if (File.Exists(otherConfigurationFile))
                {
                    File.Delete(otherConfigurationFile);
                }
            }
        }
        // Show how to use different modalities to save
        // a configuration file.
        static void SaveConfigurationFile()
        {
            try
            {

                // Get the current configuration file.
                System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                        ConfigurationUserLevel.None) as System.Configuration.Configuration;

                // Save the full configuration file and force save even if the file was not modified.
                config.SaveAs("MyConfigFull.config", ConfigurationSaveMode.Full, true);
                Console.WriteLine("Saved config file as MyConfigFull.config using the mode: {0}",
                                  ConfigurationSaveMode.Full.ToString());

                config =
                    ConfigurationManager.OpenExeConfiguration(
                        ConfigurationUserLevel.None) as System.Configuration.Configuration;

                // Save only the part of the configuration file that was modified.
                config.SaveAs("MyConfigModified.config", ConfigurationSaveMode.Modified, true);
                Console.WriteLine("Saved config file as MyConfigModified.config using the mode: {0}",
                                  ConfigurationSaveMode.Modified.ToString());

                config =
                    ConfigurationManager.OpenExeConfiguration(
                        ConfigurationUserLevel.None) as System.Configuration.Configuration;

                // Save the full configuration file.
                config.SaveAs("MyConfigMinimal.config");
                Console.WriteLine("Saved config file as MyConfigMinimal.config using the mode: {0}",
                                  ConfigurationSaveMode.Minimal.ToString());

            }
            catch (ConfigurationErrorsException err)
            {
                Console.WriteLine("SaveConfigurationFile: {0}", err.ToString());
            }
        }
Пример #8
0
        private void ExecuteConfigurationSave()
        {
            ConfigurationSaveMode saveMode = m_saveMode;

            m_userConfiguration.Save(saveMode == ConfigurationSaveMode.Full);
            m_configuration.Save(saveMode, m_forceSave);
            m_forceSave = false;

            try
            {
                // Attempt to create a backup configuration file
#if MONO
                m_configuration.SaveAs(BackupConfigFilePath, ConfigurationSaveMode.Full);
#else
                File.Copy(m_configuration.FilePath, BackupConfigFilePath, true);
#endif
            }
            catch
            {
                // May not have needed rights to save backup configuration file
            }
        }
Пример #9
0
        /// <summary>
        /// Commits the changes to disk and force a reload.
        /// </summary>
        /// <param name="config">The configuration.</param>
        /// <param name="filePath">The file path where the configuration should be saved.</param>
        /// <remarks>
        /// This method is very framework dependant.  The current implementation is only known to work in .NET 4.0
        /// </remarks>
        public static void Commit(this System.Configuration.Configuration config, string filePath)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }


            if (string.IsNullOrWhiteSpace(filePath) || string.Equals(Path.GetFileName(config.FilePath), Path.GetFileName(filePath)))
            {
                config.Save(ConfigurationSaveMode.Minimal);
            }
            else
            {
                config.SaveAs(filePath, ConfigurationSaveMode.Minimal);
            }

            Type         t     = typeof(ConfigurationManager);
            BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Static;

            // clear the configuration state
            FieldInfo field;

            field = t.GetField("s_initState", flags);
            if (field == null)
            {
                throw new InvalidOperationException($"The field s_initState is no longer present.");
            }
            field.SetValue(null, 0);

            field = t.GetField("s_configSystem", flags);
            if (field == null)
            {
                throw new InvalidOperationException("The field s_configSystem is no longer present.");
            }
            field.SetValue(null, null);

            // force a reload
            MethodInfo method = t.GetMethod("PrepareConfigSystem", flags);

            if (method == null)
            {
                throw new InvalidOperationException("The method PrepareConfigSystem is no longer present.");
            }
            method.Invoke(null, null);
        }
Пример #10
0
        public void SaveConfigurationFile(IEnumerable <SectionMigrated> sections)
        {
            try
            {
                DirectoryInfo destination = new DirectoryInfo(_destinationPath);


                if (!destination.Exists)
                {
                    destination.Create();
                }
                var destinationFile = SetupDestinationFile(destination);

                System.Configuration.Configuration configurationToModify = ConfigurationManager.OpenExeConfiguration(destinationFile.FullName);
                foreach (var section in sections)
                {
                    configurationToModify.Sections.Add(section.SectionName, new YourConfigIsInAnotherCastle.InAnotherCastleConfigSectionRedirect()
                    {
                        CacheDurationInMinutes = 60,
                        SystemName             = null, // todo
                        Name = section.SectionName,    //TODO allow change
                        Type = section.SectionTypeName,
                        Mode = Mode.Standard,
                    });
                    configurationToModify.Sections[section.SectionName].SectionInformation.Type = typeof(InAnotherCastleHandler).AssemblyQualifiedName;
                }
                configurationToModify.ConnectionStrings.ConnectionStrings.Clear();
                configurationToModify.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings()
                {
                    ConnectionString = this._connectionString,
                    Name             = DefaultServiceProvider.ConnectionStringKey,
                    ProviderName     = "System.Data.SqlClient"
                });

                configurationToModify.SaveAs(destinationFile.FullName, ConfigurationSaveMode.Full);
            }
            catch (IOException ioException)
            {
                throw new MigrationException("IO exception occurred while creating migrated configuration file", ioException);
            }
            catch (ConfigurationException configException)
            {
                throw new MigrationException("Configuration exception occurred while creating migrated configuration file", configException);
            }
        }
        public T SaveAs(
            [NotNull] string filename,
            ConfigurationSaveMode saveMode = ConfigurationSaveMode.Modified,
            bool forceSaveAll = false)
        {
            if (IsDisposed)
            {
                throw new ObjectDisposedException(ToString());
            }

            System.Configuration.Configuration configuration = CurrentConfiguration;
            if (string.IsNullOrWhiteSpace(filename) || configuration == null)
            {
                throw new ConfigurationErrorsException(Resources.ConfigurationSection_Save_No_Configuration);
            }

            // If this is the active configuration, ensure it is unloaded, this will make it impossible the file
            // save event will be raised against the active configuration.
            // ReSharper disable once ExceptionNotDocumented
            bool wasActive = ReferenceEquals(Interlocked.CompareExchange(ref _active, null, (T)this), this);

            if (string.Equals(filename, configuration.FilePath))
            {
                configuration.Save(saveMode, forceSaveAll);
            }
            else
            {
                configuration.SaveAs(filename, saveMode, forceSaveAll);
            }

            // Tell the configuration manager to refresh the section.
            ConfigurationManager.RefreshSection(SectionName);

            // We dispose as any saved configuration must be reloaded before being used again.
            Dispose();

            T config = LoadOrCreate(filename);

            if (wasActive)
            {
                Active = config;
            }

            return(config);
        }
Пример #12
0
        public void SaveAs(string path)
        {
            if (this._ConfigurationPath == path)
            {
                path = (string)null;
            }
            System.Configuration.Configuration configuration = this.OpenConfiguration();
            if (!string.IsNullOrEmpty(path))
            {
                this._ConfigurationPath = path;
            }
            GeneratorSection section = configuration.GetSection("WCFGenerator") as GeneratorSection;

            section.ServicesSettings.IsGenerateAll         = this._IsGenerateAll;
            section.ServicesSettings.IsGenerateSilverlight = this._IsGenerateSilverlight;
            section.ServicesSettings.Address        = this._Address;
            section.ServicesSettings.LogNaming      = this._LogNaming;
            section.ServicesSettings.LogPath        = this._LogPath;
            section.ServicesSettings.LogXmlDocument = this._LogXmlDocument;
            section.ServicesSettings.UseSSL         = this._UseSSL;
            section.ServicesSettings.ProcessTxnGUID = this._ProcessTxnGUID;
            section.GeneratedAssemblySettings.ClientOutputConfigPath           = this._ClientOutputConfigPath;
            section.GeneratedAssemblySettings.ClientOutputDirectory            = this._ClientOutputDirectory;
            section.GeneratedAssemblySettings.ClientSilverlightOutputDirectory = this._ClientSilverlightOutputDirectory;
            section.GeneratedAssemblySettings.ServerOutputDirectory            = this._ServerOutputDirectory;
            section.ConnectionSettings.DatabaseConnectionString      = this._DatabaseConnectionString;
            section.ConnectionSettings.DefaultServerConnectionString = this._DefaultServerConnectionString;
            section.ConnectionSettings.IsGetFromRegistry             = this._IsGetFromRegistry;
            section.ConnectionSettings.ConnectionStrings             = this._ConnectionStrings;
            if (string.IsNullOrEmpty(path))
            {
                configuration.Save();
            }
            else
            {
                configuration.SaveAs(this._ConfigurationPath);
            }
        }
Пример #13
0
        public Boolean Load(string sectionName = "ModConfigSection")
        {
            bool result = false;

            //!TODO cleaning of private variables, making it ready for loading, removing old loaded instances
            typeFactory.DeepSearch = true;
            typeFactory.LoadPreloadedAssemblies();

            System.Configuration.Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ModConfigSection section = configuration.GetSection(sectionName) as ModConfigSection;

            configuration.SaveAs(".\\somewhere\\external.xml", ConfigurationSaveMode.Full, true);

            if (section != null)
            {
                pluginsLoaded = LoadPlugins(section.PluginCollection);
                if (pluginsLoaded)
                {
                    modulesLoaded = LoadModules(section.ModuleConfigCollection, 0);
                    if (modulesLoaded)
                    {
                        for (int i = 0; i < modules.Count; i++)
                        {
                            IInitiator initiator = modules[i].Instance as IInitiator;
                            if (initiator != null)
                            {
                                if ((initiator.Initialize() == false) && !initiator.IsInitialized)
                                {
                                    throw new ConfigurationErrorsException("Couldn't load " + modules[i].Type);
                                }
                            }
                        }
                        result = true;
                    }
                }
            }
            return(result);
        }
Пример #14
0
    // </Snippet4>

    // <Snippet9>

    // Access a configuration file using mapping.
    // This function uses the OpenMappedExeConfiguration
    // method to access a new configuration file.
    // It also gets the custom ConsoleSection and
    // sets its ConsoleElement BackgroundColor and
    // ForegroundColor properties to green and red
    // respectively. Then it uses these properties to
    // set the console colors.
    public static void MapExeConfiguration()
    {
        // Get the application configuration file.
        System.Configuration.Configuration config =
            ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

        Console.WriteLine(config.FilePath);

        if (config == null)
        {
            Console.WriteLine(
                "The configuration file does not exist.");
            Console.WriteLine(
                "Use OpenExeConfiguration to create the file.");
        }

        // Create a new configuration file by saving
        // the application configuration to a new file.
        string appName =
            Environment.GetCommandLineArgs()[0];

        string configFile = string.Concat(appName,
                                          ".2.config");

        config.SaveAs(configFile, ConfigurationSaveMode.Full);

        // Map the new configuration file.
        ExeConfigurationFileMap configFileMap =
            new ExeConfigurationFileMap();

        configFileMap.ExeConfigFilename = configFile;

        // Get the mapped configuration file
        config =
            ConfigurationManager.OpenMappedExeConfiguration(
                configFileMap, ConfigurationUserLevel.None);

        // Make changes to the new configuration file.
        // This is to show that this file is the
        // one that is used.
        string sectionName = "consoleSection";

        ConsoleSection customSection =
            (ConsoleSection)config.GetSection(sectionName);

        if (customSection == null)
        {
            customSection = new ConsoleSection();
            config.Sections.Add(sectionName, customSection);
        }
        else
        {
            // Change the section configuration values.
            customSection =
                (ConsoleSection)config.GetSection(sectionName);
        }

        customSection.ConsoleElement.BackgroundColor =
            ConsoleColor.Green;
        customSection.ConsoleElement.ForegroundColor =
            ConsoleColor.Red;

        // Save the configuration file.
        config.Save(ConfigurationSaveMode.Modified);

        // Force a reload of the changed section. This
        // makes the new values available for reading.
        ConfigurationManager.RefreshSection(sectionName);

        // Set console properties using the
        // configuration values contained in the
        // new configuration file.
        Console.BackgroundColor =
            customSection.ConsoleElement.BackgroundColor;
        Console.ForegroundColor =
            customSection.ConsoleElement.ForegroundColor;
        Console.Clear();

        Console.WriteLine();
        Console.WriteLine("Using OpenMappedExeConfiguration.");
        Console.WriteLine("Configuration file is: {0}",
                          config.FilePath);
    }
Пример #15
0
        public CoreSettings()
        {
            ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();
            exeConfigurationFileMap.ExeConfigFilename = new FileInfo("Config.xml").FullName;
            if (File.Exists(exeConfigurationFileMap.ExeConfigFilename))
            {
                m_Configuration = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
                //2008-04-07 Nochbaer: Check Settings
                bool needtowrite = false;
                String[] keys = m_Configuration.AppSettings.Settings.AllKeys;
                Predicate<String> key;
                key = delegate(String StringToMatch) { return StringToMatch == "ActivateOnlineSignature"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("ActivateOnlineSignature", "False");
                    needtowrite = true;
                }
                //2009-01-25 Nochbaer
                key = delegate(String StringToMatch) { return StringToMatch == "ActivateSearchDB"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("ActivateSearchDB", "False");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "AutoMoveDownloads"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("AutoMoveDownloads", "False");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "AutoMoveDownloadsIntervall"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("AutoMoveDownloadsIntervall", "60");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "AverageConnectionsCount"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("AverageConnectionsCount", "5");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "ConfigurationFile"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("ConfigurationFile", "Config.xml");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "CorruptDirectory"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("CorruptDirectory", "corrupt");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "DownloadCapacity"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("DownloadCapacity", "131072");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "DownloadLimit"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("DownloadLimit", "65536");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "FirstStart"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("FirstStart", "False");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "HasDownloadLimit"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("HasDownloadLimit", "False");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "HasUploadLimit"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("HasUploadLimit", "False");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "IncomingDirectory"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("IncomingDirectory", "incoming");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "LogDirectory"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("LogDirectory", "log");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "MaximumDownloadsCount"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("MaximumDownloadsCount", "6");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "MaxSearchDBResults"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("MaxSearchDBResults", "1000");
                    needtowrite = true;
                }
                //2008-07-24 Nochbaer: BZ 45
                key = delegate(String StringToMatch) { return StringToMatch == "NewDownloadsToBeginngingOfQueue"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("NewDownloadsToBeginngingOfQueue", "False");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "OnlineSignatureUpdateIntervall"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("OnlineSignatureUpdateIntervall", "5");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "ParseCollections"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("ParseCollections", "True");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "Port"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("Port", "6097");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "PreferencesDirectory"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("PreferencesDirectory", "preferences");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "PreviewFiletypes"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("PreviewFiletypes", "wmv|mov|asf|avi|mpeg|mpg|mp3|flac|ogg|wav|wma");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "PreviewPlayer"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("PreviewPlayer", "");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "PreviewParams"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("PreviewParams", "");
                    needtowrite = true;
                }
                //2009-01-25 Nochbaer
                key = delegate(String StringToMatch) { return StringToMatch == "SearchDBCleanUpDays"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("SearchDBCleanUpDays", "7");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "SubFoldersForCollections"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("SubFoldersForCollections", "True");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "SynchronizeWebCaches"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("SynchronizeWebCaches", "True");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "TemporaryDirectory"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("TemporaryDirectory", "temp");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "UICulture"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("UICulture", "en");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "UploadCapacity"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("UploadCapacity", "16384");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "UploadLimit"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("UploadLimit", "8192");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "UseBytesInsteadOfBits"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("UseBytesInsteadOfBits", "False");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "UserWasAsked"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("UserWasAsked", "False");
                    needtowrite = true;
                }
                key = delegate(String StringToMatch) { return StringToMatch == "WriteLogfile"; };
                if (!Array.Exists<String>(keys, key))
                {
                    m_Configuration.AppSettings.Settings.Add("WriteLogfile", "True");
                    needtowrite = true;
                }

                if (needtowrite)
                    m_Configuration.Save();
            }
            else
            {
                m_Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                m_Configuration.AppSettings.Settings.Add("ActivateOnlineSignature", "False");
                m_Configuration.AppSettings.Settings.Add("ActivateSearchDB", "False");
                m_Configuration.AppSettings.Settings.Add("AutoMoveDownloads", "False");
                m_Configuration.AppSettings.Settings.Add("AutoMoveDownloadsIntervall", "60");
                m_Configuration.AppSettings.Settings.Add("AverageConnectionsCount", "5");
                m_Configuration.AppSettings.Settings.Add("ConfigurationFile", "Config.xml");
                m_Configuration.AppSettings.Settings.Add("CorruptDirectory", "corrupt");
                m_Configuration.AppSettings.Settings.Add("DownloadCapacity", "131072");
                m_Configuration.AppSettings.Settings.Add("DownloadLimit", "65536");
                m_Configuration.AppSettings.Settings.Add("FirstStart", "False");
                m_Configuration.AppSettings.Settings.Add("HasDownloadLimit", "False");
                m_Configuration.AppSettings.Settings.Add("HasUploadLimit", "False");
                m_Configuration.AppSettings.Settings.Add("IncomingDirectory", "incoming");
                m_Configuration.AppSettings.Settings.Add("LogDirectory", "log");
                m_Configuration.AppSettings.Settings.Add("MaximumDownloadsCount", "5");
                m_Configuration.AppSettings.Settings.Add("MaxSearchDBResults", "1000");
                m_Configuration.AppSettings.Settings.Add("NewDownloadsToBeginngingOfQueue", "False");
                m_Configuration.AppSettings.Settings.Add("OnlineSignatureUpdateIntervall", "5");
                m_Configuration.AppSettings.Settings.Add("ParseCollections", "True");
                m_Configuration.AppSettings.Settings.Add("Port", "6097");
                m_Configuration.AppSettings.Settings.Add("PreferencesDirectory", "preferences");
                m_Configuration.AppSettings.Settings.Add("PreviewFiletypes", "wmv|mov|asf|avi|mpeg|mpg|mp3|flac|ogg|wav|wma");
                m_Configuration.AppSettings.Settings.Add("PreviewPlayer", "");
                m_Configuration.AppSettings.Settings.Add("PreviewParams", "");
                m_Configuration.AppSettings.Settings.Add("SearchDBCleanUpDays", "7");
                m_Configuration.AppSettings.Settings.Add("SubFoldersForCollections", "True");
                m_Configuration.AppSettings.Settings.Add("SynchronizeWebCaches", "True");
                m_Configuration.AppSettings.Settings.Add("TemporaryDirectory", "temp");
                m_Configuration.AppSettings.Settings.Add("UICulture", "en");
                m_Configuration.AppSettings.Settings.Add("UploadCapacity", "16384");
                m_Configuration.AppSettings.Settings.Add("UploadLimit", "8192");
                m_Configuration.AppSettings.Settings.Add("UseBytesInsteadOfBits", "False");
                m_Configuration.AppSettings.Settings.Add("UserWasAsked", "False");
                m_Configuration.AppSettings.Settings.Add("WriteLogfile", "True");
                m_Configuration.SaveAs(exeConfigurationFileMap.ExeConfigFilename);
            }
        }
Пример #16
0
        static void Main(string[] args)
        {
            //<snippet1>
            // Obtains the machine configuration settings on the local machine.
            System.Configuration.Configuration machineConfig =
                System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration();
            machineConfig.SaveAs("c:\\machineConfig.xml");
            //</snippet1>


            //<snippet2>
            // Obtains the configuration settings for a Web application.
            System.Configuration.Configuration webConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            webConfig.SaveAs("c:\\webConfig.xml");
            //</snippet2>


            //<snippet3>
            // Obtains the configuration settings for the <anonymousIdentification> section.
            System.Configuration.Configuration config =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            System.Web.Configuration.SystemWebSectionGroup systemWeb =
                config.GetSectionGroup("system.web")
                as System.Web.Configuration.SystemWebSectionGroup;
            System.Web.Configuration.AnonymousIdentificationSection sectionConfig =
                systemWeb.AnonymousIdentification;
            if (sectionConfig != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<anonymousIdentification> attributes:\r\n");
                System.Configuration.PropertyInformationCollection props =
                    sectionConfig.ElementInformation.Properties;
                foreach (System.Configuration.PropertyInformation prop in props)
                {
                    sb.AppendFormat("{0} = {1}\r\n", prop.Name.ToString(), prop.Value.ToString());
                }
                Console.WriteLine(sb.ToString());
            }
            //</snippet3>


            //<snippet4>
            IntPtr userToken = System.Security.Principal.WindowsIdentity.GetCurrent().Token;

            // Obtains the machine configuration settings on a remote machine.
            System.Configuration.Configuration remoteMachineConfig =
                System.Web.Configuration.WebConfigurationManager.OpenMachineConfiguration
                    (null, "ServerName", userToken);
            remoteMachineConfig.SaveAs("c:\\remoteMachineConfig.xml");

            // Obtains the root Web configuration settings on a remote machine.
            System.Configuration.Configuration remoteRootConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
                    (null, null, null, "ServerName", userToken);
            remoteRootConfig.SaveAs("c:\\remoteRootConfig.xml");

            // Obtains the configuration settings for the
            // W3SVC/1/Root/Temp application on a remote machine.
            System.Configuration.Configuration remoteWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration
                    ("/Temp", "1", null, "ServerName", userToken);
            remoteWebConfig.SaveAs("c:\\remoteWebConfig.xml");
            //</snippet4>


            //<snippet5>
            // Updates the configuration settings for a Web application.
            System.Configuration.Configuration updateWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Temp");
            System.Web.Configuration.CompilationSection compilation =
                updateWebConfig.GetSection("system.web/compilation")
                as System.Web.Configuration.CompilationSection;
            Console.WriteLine("Current <compilation> debug = {0}", compilation.Debug);
            compilation.Debug = true;
            if (!compilation.SectionInformation.IsLocked)
            {
                updateWebConfig.Save();
                Console.WriteLine("New <compilation> debug = {0}", compilation.Debug);
            }
            else
            {
                Console.WriteLine("Could not save configuration.");
            }
            //</snippet5>


            //<snippet6>
            System.Configuration.Configuration rootWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
            System.Configuration.ConnectionStringSettings connString;
            if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
            {
                connString =
                    rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
                if (connString != null)
                {
                    Console.WriteLine("Northwind connection string = \"{0}\"",
                                      connString.ConnectionString);
                }
                else
                {
                    Console.WriteLine("No Northwind connection string");
                }
            }
            //</snippet6>


            //<snippet7>
            System.Configuration.Configuration rootWebConfig1 =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
            if (rootWebConfig1.AppSettings.Settings.Count > 0)
            {
                System.Configuration.KeyValueConfigurationElement customSetting =
                    rootWebConfig1.AppSettings.Settings["customsetting1"];
                if (customSetting != null)
                {
                    Console.WriteLine("customsetting1 application string = \"{0}\"",
                                      customSetting.Value);
                }
                else
                {
                    Console.WriteLine("No customsetting1 application string");
                }
            }
            //</snippet7>
        }
Пример #17
0
        private void SaveConfig(string filePath)
        {
            if (connStrings.SectionInformation.IsProtected)
            {
                if (!connStrings.ElementInformation.IsLocked)
                {
                    connStrings.SectionInformation.UnprotectSection();

                    if (!rbNone.Checked)
                    {
                        //Protect the section.
                        string provider = ProtectedProviderName_DPAPI;
                        if (rbHKH.Checked)
                        {
                            EnsureHKHProvider();
                            provider = ProtectedProviderName_HKH;
                        }

                        connStrings.SectionInformation.ProtectSection(provider);
                    }

                    connStrings.SectionInformation.ForceSave = true;

                    if (string.IsNullOrEmpty(filePath))
                    {
                        config.Save(ConfigurationSaveMode.Full);
                    }
                    else
                    {
                        config.SaveAs(filePath, ConfigurationSaveMode.Full);
                    }
                }
                else
                {
                    MessageBox.Show(string.Format("Can't protect, section {0} is locked", connStrings.SectionInformation.Name), "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {
                if (!connStrings.ElementInformation.IsLocked)
                {
                    if (!rbNone.Checked)
                    {
                        //Protect the section.
                        string provider = ProtectedProviderName_DPAPI;
                        if (rbHKH.Checked)
                        {
                            EnsureHKHProvider();
                            provider = ProtectedProviderName_HKH;
                        }

                        connStrings.SectionInformation.ProtectSection(provider);
                    }

                    connStrings.SectionInformation.ForceSave = true;

                    if (string.IsNullOrEmpty(filePath))
                    {
                        config.Save(ConfigurationSaveMode.Full);
                    }
                    else
                    {
                        config.SaveAs(filePath, ConfigurationSaveMode.Full);
                    }
                }
                else
                {
                    MessageBox.Show(string.Format("Can't protect, section {0} is locked", connStrings.SectionInformation.Name), "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            MessageBox.Show("Save Success");
        }
 public virtual void SaveAs(string filename)
 {
     _config.SaveAs(filename);
 }
Пример #19
0
 /// <inheritdoc />
 public void SaveAs(string fileName)
 {
     _configuration.SaveAs(fileName);
 }
Пример #20
0
 /// <summary>
 /// Copies the currently executing assembly's config file to the specified
 /// path.
 /// </summary>
 /// <param name="filePath"></param>
 public static void CopyConfig(string filePath)
 {
     System.Configuration.Configuration config = GetConfig();
     config.SaveAs(filePath);
 }
Пример #21
0
 /// <summary>Writes the configuration settings contained within this <see cref="T:System.Configuration.Configuration"></see> object to the specified XML configuration file.</summary>
 /// <param name="filename">The path and file name to save the configuration file to.</param>
 /// <exception cref="T:System.Configuration.ConfigurationErrorsException">The configuration file could not be written to.- or -The configuration file has changed. </exception>
 public static void SaveAs(string filename)
 {
     Config.SaveAs(filename);
 }