2017-06-15 139 views
0

當我保存到我的XML文件時,輸入所有正確的值,並且我的代碼看起來運行平穩,正確的App.config值被保存到正確的App.config鍵,但是當我去保存到我的XML文件它不起作用。保存到XML文件不保存 - WPF

我的代碼是在這裏

的App.config:

<<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
<appSettings> 
<add key="Test" value="Entry"/> 
<add key="Directory" value="WYNW"/> 
</appSettings> 
<*More stuff*> 

我習慣叫我救

private void btnDirectory_Click(object sender, RoutedEventArgs e) 
    { 
     string oldDirectory = btnDirectory.Content.ToString(); 
     string newDirectory = grabFolder(); //Grab Folder just grabs the folder location as a string 
     if (!(string.IsNullOrWhiteSpace(newDirectory))) 
     { 
      btnDirectory.Content = newDirectory; 
      changeValue(KeyValue[1], oldDirectory, newDirectory); //KeyValue[1] is "Directory" 
     } 
    } 

我用來保存到XML

public void changeValue(string Key_Value, string Old_Value, string New_Value) 
    { 
     MessageBoxResult result = MessageBox.Show("Change " + Old_Value + " to " + New_Value + " for " + Key_Value, "Sales Vault Notifer", MessageBoxButton.YesNo); 
     switch (result) 
     { 
      case MessageBoxResult.Yes: 
       { 
        XmlDocument XMLdoc = new XmlDocument(); 
        XMLdoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); 
        foreach (XmlElement element in XMLdoc.DocumentElement) 
        { 
         if (element.Name == "appSettings") 
         { 
          foreach (XmlNode node in element.ChildNodes) 
          { 
           if (node.Attributes[0].Value == Key_Value) 
           { 
            node.Attributes[1].Value = New_Value; 
            MessageBox.Show(node.Attributes[1].Value); //Check to make sure that correct key-value has been changed ... It shows that it changes to what directory I want 
           } 
          } 
         } 
        } 
        XMLdoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); 
        break; 
       } 
     } 
    } 

一切工作順利,直到我到了XMLdoc.Save()部分。我在C#應用程序中使用了該代碼,並且它工作的很順利,但是當我切換到WPF時,MessageBoxes的Yes/No部分與我所能找到的不同並且是必需的(從我所能找到的)開始檢查,所以我假設break;是我無法保存的原因。

任何幫助,將不勝感激:)

乾杯, 亞託

回答

0

試錯後,我來到了結論:

該文件被保存,只是它一直保存到

//MyProject/bin/debugg/MyProject.exe.config

,而不是我在那裏手工編輯的

//MyProject/App.config

由於我的配置文件,通過slugster解釋here

因此,當我去開我的應用程序。配置文件在Visual Studio中沒有更改,但是當我從我的配置文件中讀取時,

using System.Configuration; 
var Variable = ConfigurationManager.AppSettings.Get("Directory"); 

已經做出了正確的改變。

希望這可以幫助誰有同樣的問題,我有:)