Как поменять в программе путь хранения настроек - C#

Узнай цену своей работы

Формулировка задачи:

Есть программа с открытым исходным кодом (LazyCure). Мне не нравится, что она сохраняет настройки в

Local Settings\Application Data

, так как пользуюсь несколькими ОСями и каждую могу раз в неделю с бекапа восстанавливать. Из-за этого приходится каждый раз заливать user.config на диск C после каждой смены системы (я часто используемые программы храню не на системном диске). Хочу сделать, чтобы программа сохраняла настройки в свою родную папку, как она это делает с другими своими файлами, но никак не получается разобраться в коде программы, прошу помощи Пробовал пошагово выполнять программу и отследил, что она их сохраняет при выполнении метода

settings.Save();

Листинг программы
  1. private void ok_Click(object sender, EventArgs e)
  2. {
  3. TimeSpan parsedReminderTime;
  4. if (TimeSpan.TryParse(reminderTime.Text, out parsedReminderTime))
  5. {
  6. CultureInfo previousUICulture = Thread.CurrentThread.CurrentUICulture;
  7. UpdateSettings(parsedReminderTime);
  8. CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;
  9. settings.Save();
  10. Dialogs.LazyCureDriver.ApplySettings(settings);
  11. Dialogs.MainForm.PostToTwitterEnabled = enableTwitterCheckbox.Checked;
  12. Dialogs.MainForm.RegisterHotKeys();
  13. Hide();
  14. if (!previousUICulture.Equals(currentUICulture))
  15. NotifyAboutLanguageApplyAfterRestart();
  16. }
  17. else
  18. MessageBox.Show(String.Format(Constants.InvalidReminderTime, reminderTime.Text), Constants.IncorrectSettings);
  19. }
Но что для меня странно и непонятно, при нажатии кнопки Step Into оно не заходит в этот метод, а пробегается по нему, как по одной команде, из-за чего не могу отловить, что именно происходит в этом методе. Класс

settings

в программе объявлен так:
Листинг программы
  1. private ISettings settings;
А интерфейс

ISettings

объявлен так:
Листинг программы
  1. public interface ISettings: ILanguageSettingsProvider
  2. {
  3. int ActivitiesNumberInTray { get; set; }
  4. string HotKeyToActivate { get; set; }
  5. string HotKeyToSwitch { get; set; }
  6. bool LeftClickOnTray { get; set; }
  7. Point MainWindowLocation { get; set; }
  8. int MaxActivitiesInHistory { get; set; }
  9. TimeSpan ReminderTime { get; set; }
  10. void Save();
  11. bool SaveAfterDone { get; set; }
  12. bool SplitByComma { get; set; }
  13. bool SwitchOnLogOff { get; set; }
  14. bool SwitchTimeLogAtMidnight { get; set; }
  15. string TimeLogsFolder { get; set; }
  16. string TweetingActivity { get; set; }
  17. string TwitterAccessToken { get; set; }
  18. string TwitterAccessTokenSecret { get; set; }
  19. bool TwitterEnabled { get; set; }
  20. bool UseTweetingActivity { get; set; }
  21. }
В нем я вижу объявление этого самого метода, но саму реализацию этого метода я не нашел, хотя изрыл поиском код вдоль и поперек Я больше не знаю, как найти этот самый метод и для меня его содержимое остается загадкой. Помогите пожалуйста! Наверное я чего-то недопонимаю или жестко туплю.... Код этого проекта открыт и доступен здесь: http://lazycure.svn.sourceforge.net/viewvc/lazycure/tags/4.0/

Решение задачи: «Как поменять в программе путь хранения настроек»

textual
Листинг программы
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Specialized;
  4. using System.Configuration;
  5. using System.IO;
  6. using System.Windows.Forms;
  7. using System.Xml;
  8.  
  9. namespace LifeIdea.LazyCure
  10. {
  11.     /// <summary>
  12.     /// PortableSettingsProvider class ensures that application settings can be saved to the application folder itself
  13.     /// instead of the user profile. Used in the configuration of Application Settings.
  14.     /// Code of Portable Settings Provider from
  15.     /// [url]http://www.codeproject.com/KB/vb/CustomSettingsProvider.aspx[/url]  (C# version by gpgemini)
  16.     /// </summary>
  17.  
  18.  
  19.     public class PortableSettingsProvider : SettingsProvider
  20.     {
  21.         private const string SETTINGSROOT = "Settings";
  22.         //XML Root Node
  23.  
  24.  
  25.         public override void Initialize(string name, NameValueCollection col)
  26.         {
  27.             base.Initialize(this.ApplicationName, col);
  28.         }
  29.  
  30.  
  31.         public override string ApplicationName
  32.         {
  33.             get
  34.             {
  35.                 if (Application.ProductName.Trim().Length > 0)
  36.                 {
  37.                     return Application.ProductName;
  38.                 }
  39.                 else
  40.                 {
  41.                     FileInfo fi = new FileInfo(Application.ExecutablePath);
  42.                     return fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);
  43.                 }
  44.             }
  45.             set { }
  46.             //Do nothing
  47.         }
  48.  
  49.  
  50.         public override string Name
  51.         {
  52.             get { return "PortableSettingsProvider"; }
  53.         }
  54.  
  55.  
  56.         public virtual string GetAppSettingsPath()
  57.         {
  58.             //Used to determine where to store the settings
  59.             System.IO.FileInfo fi = new System.IO.FileInfo(Application.ExecutablePath);
  60.             return fi.DirectoryName;
  61.         }
  62.  
  63.  
  64.         public virtual string GetAppSettingsFilename()
  65.         {
  66.             //Used to determine the filename to store the settings
  67.             return ApplicationName + ".settings";
  68.         }
  69.  
  70.  
  71.         public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection propvals)
  72.         {
  73.             //Iterate through the settings to be stored
  74.             //Only dirty settings are included in propvals, and only ones relevant to this provider
  75.             foreach (SettingsPropertyValue propval in propvals)
  76.             {
  77.                 SetValue(propval);
  78.             }
  79.  
  80.  
  81.             try
  82.             {
  83.                 SettingsXML.Save(Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename()));
  84.             }
  85.             catch (Exception)
  86.             {
  87.             }
  88.             //Ignore if cant save, device been ejected
  89.         }
  90.  
  91.  
  92.         public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context,
  93.                                                                           SettingsPropertyCollection props)
  94.         {
  95.             //Create new collection of values
  96.             SettingsPropertyValueCollection values = new SettingsPropertyValueCollection();
  97.  
  98.  
  99.             //Iterate through the settings to be retrieved
  100.             foreach (SettingsProperty setting in props)
  101.             {
  102.                 SettingsPropertyValue value = new SettingsPropertyValue(setting);
  103.                 value.IsDirty = false;
  104.                 value.SerializedValue = GetValue(setting);
  105.                 values.Add(value);
  106.             }
  107.             return values;
  108.         }
  109.  
  110.  
  111.         private XmlDocument _settingsXML = null;
  112.  
  113.  
  114.         private XmlDocument SettingsXML
  115.         {
  116.             get
  117.             {
  118.                 //If we dont hold an xml document, try opening one.  
  119.                 //If it doesnt exist then create a new one ready.
  120.                 if (_settingsXML == null)
  121.                 {
  122.                     _settingsXML = new XmlDocument();
  123.  
  124.  
  125.                     try
  126.                     {
  127.                         _settingsXML.Load(Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename()));
  128.                     }
  129.                     catch (Exception)
  130.                     {
  131.                         //Create new document
  132.                         XmlDeclaration dec = _settingsXML.CreateXmlDeclaration("1.0", "utf-8", string.Empty);
  133.                         _settingsXML.AppendChild(dec);
  134.  
  135.  
  136.                         XmlNode nodeRoot = default(XmlNode);
  137.  
  138.  
  139.                         nodeRoot = _settingsXML.CreateNode(XmlNodeType.Element, SETTINGSROOT, "");
  140.                         _settingsXML.AppendChild(nodeRoot);
  141.                     }
  142.                 }
  143.  
  144.  
  145.                 return _settingsXML;
  146.             }
  147.         }
  148.  
  149.  
  150.         private string GetValue(SettingsProperty setting)
  151.         {
  152.             string ret = "";
  153.  
  154.  
  155.             try
  156.             {
  157.                 if (IsRoaming(setting))
  158.                 {
  159.                     ret = SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + setting.Name).InnerText;
  160.                 }
  161.                 else
  162.                 {
  163.                     ret =
  164.                         SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + Environment.MachineName + "/" + setting.Name).
  165.                             InnerText;
  166.                 }
  167.             }
  168.  
  169.  
  170.             catch (Exception)
  171.             {
  172.                 if ((setting.DefaultValue != null))
  173.                 {
  174.                     ret = setting.DefaultValue.ToString();
  175.                 }
  176.                 else
  177.                 {
  178.                     ret = "";
  179.                 }
  180.             }
  181.  
  182.  
  183.             return ret;
  184.         }
  185.  
  186.  
  187.         private void SetValue(SettingsPropertyValue propVal)
  188.         {
  189.             XmlElement MachineNode = default(XmlElement);
  190.             XmlElement SettingNode = default(XmlElement);
  191.  
  192.  
  193.             //Determine if the setting is roaming.
  194.             //If roaming then the value is stored as an element under the root
  195.             //Otherwise it is stored under a machine name node
  196.             try
  197.             {
  198.                 if (IsRoaming(propVal.Property))
  199.                 {
  200.                     SettingNode = (XmlElement)SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + propVal.Name);
  201.                 }
  202.                 else
  203.                 {
  204.                     SettingNode =
  205.                         (XmlElement)
  206.                         SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + Environment.MachineName + "/" + propVal.Name);
  207.                 }
  208.             }
  209.             catch (Exception)
  210.             {
  211.                 SettingNode = null;
  212.             }
  213.  
  214.  
  215.             //Check to see if the node exists, if so then set its new value
  216.             if ((SettingNode != null))
  217.             {
  218.                 SettingNode.InnerText = Convert.ToString(propVal.SerializedValue);
  219.             }
  220.             else
  221.             {
  222.                 if (IsRoaming(propVal.Property))
  223.                 {
  224.                     //Store the value as an element of the Settings Root Node
  225.                     SettingNode = SettingsXML.CreateElement(propVal.Name);
  226.                     SettingNode.InnerText = propVal.SerializedValue.ToString();
  227.                     SettingsXML.SelectSingleNode(SETTINGSROOT).AppendChild(SettingNode);
  228.                 }
  229.                 else
  230.                 {
  231.                     //Its machine specific, store as an element of the machine name node,
  232.                     //creating a new machine name node if one doesnt exist.
  233.                     try
  234.                     {
  235.                         MachineNode =
  236.                             (XmlElement)SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + Environment.MachineName);
  237.                     }
  238.                     catch (Exception)
  239.                     {
  240.                         MachineNode = SettingsXML.CreateElement(Environment.MachineName);
  241.                         SettingsXML.SelectSingleNode(SETTINGSROOT).AppendChild(MachineNode);
  242.                     }
  243.  
  244.  
  245.                     if (MachineNode == null)
  246.                     {
  247.                         MachineNode = SettingsXML.CreateElement(Environment.MachineName);
  248.                         SettingsXML.SelectSingleNode(SETTINGSROOT).AppendChild(MachineNode);
  249.                     }
  250.  
  251.  
  252.                     SettingNode = SettingsXML.CreateElement(propVal.Name);
  253.                     SettingNode.InnerText = Convert.ToString(propVal.SerializedValue);
  254.                     MachineNode.AppendChild(SettingNode);
  255.                 }
  256.             }
  257.         }
  258.  
  259.  
  260.         private bool IsRoaming(SettingsProperty prop)
  261.         {
  262.             //Determine if the setting is marked as Roaming
  263.             foreach (DictionaryEntry d in prop.Attributes)
  264.             {
  265.                 Attribute a = (Attribute)d.Value;
  266.                 if (a is System.Configuration.SettingsManageabilityAttribute)
  267.                 {
  268.                     return true;
  269.                 }
  270.             }
  271.             return false;
  272.         }
  273.     }
  274. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 3.9 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы