Windows Phone应用程序中找不到文件异常

时间:2014-07-21 11:00:15

标签: c# xml windows-phone-8.1

我正在开发一个应用程序来操作Windows Phone 8.1 RT中的XML。代码在

之下
private void btnXcute_tapped(object sender, TappedRoutedEventArgs e)
{
    xmlmanipulation();
}

private async void xmlmanipulation()
{
    Random rand = new Random();
    try
    {
        var filex = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(@"xmlfile.xml");
        XDocument xdoc = XDocument.Load(filex);
        var word = xdoc.Descendants("word");
        int max = word.Count();
        txt1.Text = word.FirstOrDefault().Value.ToString();
        txt1_Copy.Text = xdoc.Descendants("meaning").FirstOrDefault().Value.ToString();

        //node removal part
        xdoc.Root.Elements("wordset").Where(dim_word => dim_word.Element("word").Value == word.FirstOrDefault().Value.ToString() && dim_word.Element("meaning").Value == xdoc.Descendants("meaning").FirstOrDefault().Value.ToString())
            .FirstOrDefault().Remove();

        //file overwriting part
        var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("xmlfile.xml", CreationCollisionOption.ReplaceExisting);
        using (var stream = await file.OpenStreamForWriteAsync())
        {
            xdoc.Save(stream);      // Save XDocument into the stream
            stream.Position = 0;
        }
    }
    catch (Exception s) 
    {
        txt1.Text = s.Message;
        txt1_Copy.Text = s.Source;

    }
}

我已将XML文件(xmlfile.xml)放在项目主文件夹中,如下所示 enter image description here

但我得到The system cannot find the file specified. (Exception from HRESULT:0x80070002),而异常来源是mscorlib

我是XML操作的新手。请帮我。我需要读取一个XML文件,重新编写其上的第一个<wordset>元素,在按钮单击上保存文件(覆盖)。我总共有4个<wordset>个元素,如果按下按钮4次,则会删除文件中的所有元素。

我的XML文件是

<?xml version="1.0" encoding="utf-8" ?>
<xmlfile>
  <wordset>
    <word>word1</word>
    <meaning>meaning1</meaning>
  </wordset>
  <wordset>
    <word>word2</word>
    <meaning>meaning2</meaning>
  </wordset>
  <wordset>
    <word>word3</word>
    <meaning>meaning3</meaning>
  </wordset>
  <wordset>
    <word>word4</word>
    <meaning>meaning4</meaning>
  </wordset>
</xmlfile>

1 个答案:

答案 0 :(得分:2)

您正尝试从已安装的位置而不是 LocalFolder 访问文件(取决于文件的构建操作)。因此,您应该使用:

var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// not:
var folder = ApplicationData.Current.LocalFolder;

您还可以查看this answer