2013-08-01 26 views
0

這是在intel-sense中返回正確的元素原因nexp讀取 這樣離線我試圖將離線值的元素更改爲就緒。Linq查詢對象引用未設置爲對象的實例。 2

public void ChangeConnectionStatus(string SelectedFile) 
     { 
     System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(@"C:\Users\Rick\Documents\Visual Studio 2010\Projects\Server\server.config\DC_Classes\"); 
      //Getting All file names from the directory info 
      System.IO.FileInfo[] fileNames = dirInfo.GetFiles(SelectedFile + "*.xml*"); 
      //Foreach itterator 
      foreach (System.IO.FileInfo fi in fileNames) 
      { 
       XElement main = XElement.Load(fi.FullName); 

       IEnumerable<XElement> Nongroups = from nexp in main.XPathSelectElements("Network/Posted_Status") 
          where nexp.Element("Posted_Status").Value == "Offline" 
          select nexp; 
      ////Handle the process here 
      foreach (XElement nexp in Nongroups) 
      { 
       DialogResult Yes = MessageBox.Show("This Will Online This Group Are You Sure You Want To Do This","System Info",MessageBoxButtons.YesNo,MessageBoxIcon.Information); 
       if (Yes == DialogResult.Yes) 
       { 
        nexp.SetValue("Ready"); 
       } 
      } 
      } 

     } 
+1

看起來像「Posted_Status」元素可能不存在,因此'.Value'會拋出。您可以使用顯式轉換運算符而不是'.Value'像這樣'(string)nexp.Element(「Posted_Status」)' – Pawel

+0

您的XML看起來像什麼? –

回答

0

如果你不能確定物體的類型,那麼就使用var

foreach (var nexp in Nongroups) 

並以這種方式分配值:

if (Yes == DialogResult.Yes) 
{ 
    nexp.Element("Posted_Status").Value = "Ready"; 
} 
0

我的猜測是,你缺少命名空間,你可以在this SO線程中看到。所以,我期待nexp被設置爲null,在這條線:在main.XPathSelectElements( 「網絡/ Posted_Status」)

NEXP

您可以閱讀MSDN thread爲好。

試試看,希望它有幫助!

+0

我把我的代碼改爲了現在的數字現在它說它是一個空引用 – shawn

+0

你能否讓你的查詢這樣,看看會發生什麼:'IEnumerable Nongroups =從nexp在main.XPathSelectElements(「Network/Posted_Status」)select nexp ' – NeverHopeless

相關問題