Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

Мне нужен код на c#. Эта процедура в которую передается (string Param, string Value).…

  1. User

    Мне нужен код на c#. Эта процедура в которую передается (string Param, string Value). Входящие параметры записываются в XML файл где лежит exe файл приложения. Вторая процедура читает эти значения и возвращает тип string. Но имеет всего входной параметр типа стринг по которому находит нужный параметр для чтения.

  2. Assistant

    Приведенный ниже код демонстрирует пример реализации требуемых процедур:

    using System;
    using System.IO;
    using System.Xml;
    
    public class Program
    {
        public static void Main()
        {
            // Пример использования
            WriteParamValue("param1", "value1");
            WriteParamValue("param2", "value2");
            
            Console.WriteLine(ReadParamValue("param1")); // Выводит "value1"
            Console.WriteLine(ReadParamValue("param2")); // Выводит "value2"
        }
        
        // Процедура для записи параметра и его значения в XML файл
        public static void WriteParamValue(string Param, string Value)
        {
            string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;
            string xmlPath = Path.ChangeExtension(exePath, "xml");
            
            XmlDocument xmlDoc = new XmlDocument();
            if (File.Exists(xmlPath))
            {
                xmlDoc.Load(xmlPath);
            }
            else
            {
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                XmlElement root = xmlDoc.DocumentElement;
                xmlDoc.InsertBefore(xmlDeclaration, root);
            }
            
            XmlElement paramElement = xmlDoc.CreateElement("Param");
            paramElement.SetAttribute("Name", Param);
            paramElement.InnerText = Value;
            
            xmlDoc.DocumentElement.AppendChild(paramElement);
            xmlDoc.Save(xmlPath);
        }
        
        // Процедура для чтения значения параметра из XML файла по его имени
        public static string ReadParamValue(string Param)
        {
            string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;
            string xmlPath = Path.ChangeExtension(exePath, "xml");
            
            XmlDocument xmlDoc = new XmlDocument();
            if (File.Exists(xmlPath))
            {
                xmlDoc.Load(xmlPath);
                
                XmlNodeList paramNodes = xmlDoc.GetElementsByTagName("Param");
                foreach (XmlNode paramNode in paramNodes)
                {
                    string name = paramNode.Attributes["Name"].Value;
                    
                    if (name == Param)
                    {
                        return paramNode.InnerText;
                    }
                }
            }
            
            return null;
        }
    }
    

    В данном примере предполагается, что XML файл будет иметь следующую структуру:

    <?xml version="1.0" encoding="UTF-8"?>
    <Params>
        <Param Name="param1">value1</Param>
        <Param Name="param2">value2</Param>
    </Params>
    

    При вызове функции WriteParamValue("param1", "value1") параметр "param1" с значением "value1" будет записан в XML файл, а функция ReadParamValue("param1") вернет значение "value1".

  3. User

    public static void WriteParamValue(string Param, string Value) { string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;

            string xmlPath = Path.ChangeExtension(exePath, "xml");
    
            XmlDocument xmlDoc = new XmlDocument();
    
            if (File.Exists(xmlPath))
            {
                xmlDoc.Load(xmlPath);
            }
            else
            {
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF - 8", null);
                XmlElement root = xmlDoc.DocumentElement;
                xmlDoc.InsertBefore(xmlDeclaration, root);
            }
    
            XmlElement paramElement = xmlDoc.CreateElement("Param");
            paramElement.SetAttribute("Name", Param);
            paramElement.InnerText = Value;
    
            xmlDoc.DocumentElement.AppendChild(paramElement);
            xmlDoc.Save(xmlPath);
        } jib,rf dcnhjrt
    
  4. Assistant

    Ошибка в данном коде связана с использованием недопустимого символа при создании XmlDeclaration. Замените "UTF - 8" на "UTF-8" (без пробела) в следующей строке:

    XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF - 8", null);
    

    Исправленный код будет выглядеть следующим образом:

    public static void WriteParamValue(string Param, string Value)
    {
        string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;
    
        string xmlPath = Path.ChangeExtension(exePath, "xml");
    
        XmlDocument xmlDoc = new XmlDocument();
    
        if (File.Exists(xmlPath))
        {
            xmlDoc.Load(xmlPath);
        }
        else
        {
            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            XmlElement root = xmlDoc.DocumentElement;
            xmlDoc.InsertBefore(xmlDeclaration, root);
        }
    
        XmlElement paramElement = xmlDoc.CreateElement("Param");
        paramElement.SetAttribute("Name", Param);
        paramElement.InnerText = Value;
    
        xmlDoc.DocumentElement.AppendChild(paramElement);
        xmlDoc.Save(xmlPath);
    }