簡體   English   中英

streamreader 讀取 xml 文件,然后 file.move 移動 xml 文件 - c#

[英]streamreader to read xml file and then file.move to move the xml file - c#

使用 Jon Skeet 的代碼

static IEnumerable<XElement> SimpleStreamAxis(string inputUrl,
                                              string elementName)
{
  using (XmlReader reader = XmlReader.Create(inputUrl))
  {
    reader.MoveToContent();
    while (reader.Read())
    {
      if (reader.NodeType == XmlNodeType.Element)
      {
        if (reader.Name == elementName)
        {
          XElement el = XNode.ReadFrom(reader) as XElement;
          if (el != null)
          {
            yield return el;
          }
        }
      }
    }
  }
}

他在此線程上發帖: Jon Skeet 的解決方案

讀取數據后,我使用 File.Move(currentDest,newDest) 並且我不斷得到該文件當前正在被另一個進程使用。 我檢查過沒有打開文件的編輯器,甚至沒有瀏覽器。 另外我得到的部分路徑找不到

使用中的產量不會關閉讀者嗎? 我必須明確關閉它嗎?

文件移動代碼

File.Move(Path.Combine(InPath, "test.xml"), Path.Combine(OutPath, "test.xml"));

編輯:看起來使用流讀取器中的產量不會關閉文件。 誰能證實這一點?

您是否嘗試過在退出using塊之前顯式關閉閱讀器?

更新
當您使用 yield 時,它實際上不會做任何事情,直到您枚舉 IEnumerable。 這就是您在文件保持打開時遇到問題的原因。

請參閱此 SO 問題: 在 using() { } 塊內的 yield return 語句在執行前處理

您可能必須創建一個 IEnumerable,填充它,關閉 stream,然后返回 IEnumerable。

如果您可以使用純 Linq 到 Xml 解決方案,您可以這樣做:

static IEnumerable<XElement> SimpleStreamAxis(string filePathAndName, string elementName)
  {
     XDocument doc = XDocument.Load(filePathAndName);

     IEnumerable<XElement> results = from n in doc.Descendants(elementName) 
                   select n; 
     //Do more stuff with the results as needed...

     doc.Save(filePathAndName); //Note you can change the location by supplying a different path

     return results;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM