2012-08-23 118 views
0

我正嘗試讀取隔離存儲中創建的目錄中的書寫文件。該文件實際上正在創建。但是當讀取它,它有一個例外,「不允許操作上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); 

它實際上得到的文件名但此時有一個例外。

+1

沒有嘗試storage.OpenFile(文件名,FileMode.Open,FileAccess.Read) –

+0

是的,我沒有...它實際看到的文件名,但它給出了同樣的問題 – user1619553

+0

問題是我創建的目錄...當我嘗試使用IsolatedStorageFile時,它工作得非常好。 – user1619553

回答

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 
     } 
    } 
} 
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); 
      } 
     } 

如果這不起作用,那麼也許你的文件不存在。

+0

嗨Milani我嘗試這個和適用於我,但我有一個問題,如果我想採取的XML文件內使用'var xml = XDocument.Load(「路徑」)。ToString();''我知道方法「加載」需要流作爲參數,但我不知道如何使用,如果你能幫助我! –