从Isolatedstorage中的已创建目录中读取文件

时间:2012-08-23 13:34:45

标签: c# windows-phone-7 isolatedstorage

我正在尝试读取隔离存储中已创建目录中的写入文件。实际上正在创建该文件。但是当它被读取时,有一个例外“在IsolatedStorageFileStream上不允许操作。”......

using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (!storage.DirectoryExists("CourseworkDirectory"))
        storage.CreateDirectory("CourseworkDirectory");

    XElement Coursework = new XElement(CourseworkID);
    XDocument  _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), Coursework);
    IsolatedStorageFileStream location = new IsolatedStorageFileStream("CourseworkDirectory\\"+CourseworkID, System.IO.FileMode.Create, storage);
    StreamWriter file = new StreamWriter(location);  

    _doc.Save(file);//saving the XML document as the file
    file.Close();
    file.Dispose();//disposing the file
    location.Dispose();
}

阅读文件......

using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
    string searchpath = System.IO.Path.Combine("CourseworkDirectory", "*.*");

    foreach (string filename in storage.GetFileNames(searchpath))
    {
        XElement _xml;
        IsolatedStorageFileStream location = new IsolatedStorageFileStream(filename, System.IO.FileMode.Open, storage);

它实际上是获取文件名,但此时有一个例外。

2 个答案:

答案 0 :(得分:0)

你可以通过这样做来实现这一目标---

using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
   IsolatedStorageFileStream fileStream = storage.OpenFile(app.getSettingsPath,FileMode.Open, FileAccess.Read);
   using (StreamReader reader = new StreamReader(fileStream ))
   {
      string line;
      while((line = reader.ReadLine()) != null)
      {
         // do your work here
      }
   }
}

答案 1 :(得分:0)

试试这个,它对我有用:希望它也适合你

        String sb;

        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (myIsolatedStorage.FileExists(fileName))
            {
                StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, myIsolatedStorage));

                sb = reader.ReadToEnd();

                reader.Close();
            }

            if(!String.IsNullOrEmpty(sb))
            {
                 MessageBox.Show(sb);
            }
        }

如果这不起作用,那么您的文件可能不存在。