jjzjj

c# - 在 datagridview 中显示 .exe.config 文件并操作设置

coder 2024-06-25 原文

我正在开发一个 GUI,它能够通过 datagridview 操作 xml 文件并将其保存到用户选择的目标位置。该程序还有一个 .exe.config 文件,我还希望能够在其中自由编辑 datagridview,因为这比让用户手动进入文件并相应地更改值要方便得多。

我试过声明一个数据集,我最初认为 .exe.config 文件只是一个 xml 文件,但这段代码不起作用:

        dataSet1.ReadXml(configpath);
        bindingSource1.DataSource = dataSet1.Tables[0];
        dataGridView1.DataSource = bindingSource1;

当我运行它时,datagridview 是空的,我确认文件路径是正确的,当我调试代码时没有异常,而对于我在 GUI 中打开的其他 xml 文件,显示的数据工作得很好。也许 readxml() 只支持..合法的 xml 文件而不是 xml 配置文件?我尝试使用谷歌搜索并寻找一些答案,但我得到的只是与通过手动访问 xml 文件和更改值(我已经知道的东西)来更改设置相关的线程。我希望能够让用户对数据做他们想做的事,然后保存它。 .exe.config 设置可能也适用于另一个程序,但它本质上是一个 xml 配置文件。我认为网络上没有太多关于这个特定问题的信息,因为设置通常是静态的,如果它们发生变化,手动操作也很容易。

总结一下,

我正在寻找一种方法能够打开任何 .exe.config 文件,将其显示在数据 GridView 中,允许用户能够操作其中的数据值,然后保存文件,覆盖之前的数据设置。

感谢任何帮助。 提前致谢!

  • tf.rz(.NET 3.5 SP1,Visual Studio 2008 C#)

编辑:我将上传我创建的 xml 文件的工作示例:我有点希望程序能够导航到 .exe.config 文件,然后打开它并让它像这样显示在设置名称的位置是列,值位于 datagridview 的单元格中。不幸的是,我不在家里的电脑旁,无法执行此操作。

最佳答案

这是我用来加载和操作配置文件的。您可能希望更改 loadAppSettingsloadConnStrings 方法以满足您的需要。

using System;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;


namespace GenericManagementClasses
{
    public class ConfigFile
    {
        private string m_ConfigFilePath;
        private XmlDocument m_XmlDoc;

        private FileStream fIn;
        private StreamReader sr;
        private StreamWriter sw;

        private OrderedDictionary m_AppSettings;
        private OrderedDictionary m_ConnectionStrings;

        private XmlNode m_AppSettingsNode;
        private XmlNode m_ConnectionStringsNode;

        #region "Properties"
        public String Path
        {
            get
            {
                return m_ConfigFilePath;
            }
        }

        public OrderedDictionary AppSettings
        {
            get
            {
                return m_AppSettings;
            }
        }

        public OrderedDictionary ConnectionStrings
        {
            get
            {
                return m_ConnectionStrings;
            }
        }
        #endregion
        #region "Constructors"
        /// <summary>
        /// Default constructor - declared private so that you can't instantiate an empty ConfigFile object
        /// <code>ConfigFile cfg = new ConfigFile()</code> will result in a NotImplemented exception
        /// </summary>
        private ConfigFile()
        {
            throw new NotImplementedException("No default constructor for the ConfigFile class");
        }
        /// <summary>
        /// Public constructor
        /// <example>ConfigFile cfg = new ConfigFile(@"c:\MyApp\MyApp.exe.config");</example>
        /// </summary>
        /// <param name="ConfigFilePath">The path to the configuration file</param>
        public ConfigFile(string ConfigFilePath)
        {
            //Check to see if the file exists
            if (File.Exists(ConfigFilePath)){
                //Initialise the XmlDocument to hold the config file
                m_XmlDoc = new XmlDocument();
                //Store the path to the config file
                m_ConfigFilePath = ConfigFilePath;

                //FileStream to get the contents out of the file
                fIn = new FileStream(m_ConfigFilePath, FileMode.Open, FileAccess.ReadWrite);
                //StreamReader to read the FileStream
                sr = new StreamReader(fIn);
                //StreamWriter to write to the FileStream
                sw = new StreamWriter(fIn);

                //Try and load the XML from the file stream
                try
                {
                    m_XmlDoc.LoadXml(sr.ReadToEnd());
                    m_AppSettingsNode = m_XmlDoc.GetElementsByTagName("appSettings")[0];
                    m_ConnectionStringsNode = m_XmlDoc.GetElementsByTagName("connectionStrings")[0];

                    loadAppSettings();
                    loadConnStrings();

                }
                catch (Exception ex)
                {
                    //If it went pear shaped, throw the exception upwards
                    throw ex;
                }

            }
            else
            //If the file doesn't exist, throw a FileNotFound exception
            {
                throw new FileNotFoundException(ConfigFilePath + " does not exist");
            }
        }
        #endregion

        private void loadAppSettings()
        {
            m_AppSettings = new OrderedDictionary();
            XmlNodeList nl = m_AppSettingsNode.SelectNodes("add");
            foreach (XmlNode node in nl)
            {
                m_AppSettings.Add(node.Attributes["key"].Value, node.Attributes["value"].Value);
            }
        }

        private void loadConnStrings()
        {
            m_ConnectionStrings = new OrderedDictionary();

            XmlNodeList nl = m_ConnectionStringsNode.SelectNodes("add");
            foreach (XmlNode node in nl)
            {
                m_ConnectionStrings.Add(node.Attributes["name"].Value, node.Attributes["connectionString"].Value);
            }
        }

        public void setAppSetting(string name, string newValue)
        {
            if (!m_AppSettings.Contains(name))
            {
                throw new Exception(String.Format("Setting {0} does not exist in {1}", name, m_ConfigFilePath));
            }
            else
            {
                m_AppSettings[name] = newValue;
                m_XmlDoc.SelectSingleNode(String.Format(@"//appSettings/add[@key='{0}']",name)).Attributes["value"].Value = newValue;
                fIn.SetLength(0);
                sw.Write(m_XmlDoc.InnerXml);
                sw.Flush();
            }

        }
        #region "Static Methods"
        /// <summary>
        /// Static method to return a ConfigFile object
        /// <example>ConfigFile cfg = ConfigFile.LoadConfigFile(@c:\MyApp\MyApp.exe.config");"</example>
        /// </summary>
        /// <param name="ConfigFilePath">Path to the configuration file to load</param>
        /// <returns></returns>
        public static ConfigFile LoadConfigFile(string ConfigFilePath)
        {
            return new ConfigFile(ConfigFilePath);
        }
        #endregion
    }
}

关于c# - 在 datagridview 中显示 .exe.config 文件并操作设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6179044/

有关c# - 在 datagridview 中显示 .exe.config 文件并操作设置的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  3. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  5. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  6. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  7. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  10. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

随机推荐