class Filer { static string configPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\Orlan"; static string configFile = configPath + "\\config.xml"; static string logFile = configPath + "\\log.txt"; XDocument configFileReader; string URL = null; string softKey = null; string apiKey = null; public Filer() { try { if (!Directory.Exists(configPath)) { Directory.CreateDirectory(configPath); } if (!File.Exists(configFile)) { File.Create(configFile); } try { configFileReader = XDocument.Load(configFile); } catch { while (configFileReader == null) { File.Create(configFile); configFileReader = new XDocument(new XDeclaration("1.0", "utf8", "yes"), new XElement("root", new XElement("url"), new XElement("softKey"), new XElement("apiKey") ) ); //configFileReader.Save(configFile); } } if (configFileReader.Root.Element("url") != null) { URL = configFileReader.Root.Element("url").ToString(); } else { configFileReader.Root.Add("url"); } if (configFileReader.Root.Element("softKey") != null) { softKey = configFileReader.Root.Element("softKey").ToString(); } if (configFileReader.Root.Element("apiKey") != null) { apiKey = configFileReader.Root.Element("apiKey").ToString(); } } catch (Exception e) { this.setLog(e.ToString()); } } public string newConfig(string url, string sK, string aK) { string result; if (url.Length == 0) { result = "Задан пустой адрес обращения!"; } else if (sK.Length == 0) { result = "Задан пустой soft_key!"; } else if (aK.Length == 0) { result = "Задан пустой api_key!"; } else { configFileReader.Root.Element("url").Value = url; configFileReader.Root.Element("softKey").Value = sK; configFileReader.Root.Element("apiKey").Value = aK; configFileReader.Save(configFile); result = "Данные для подключения сохранены."; } return result; } public void setLog(string exception) { File.AppendAllText(logFile, exception + Environment.NewLine + "===================" + Environment.NewLine); } }
The essence of the class is that it reads the necessary data from the file, if the file is not present, the file is created and filled with data.
When you try to set and save using newConfig (), it indicates that you cannot access the file because already in use.