2011-05-29 61 views
3

我在一個解決方案中有兩個Windows窗體應用程序和庫。如何爲兩個Windows窗體應用程序共享一個IsolatedStorage?

庫類可以在IsolatedStorage中創建新的文件夾和文件,並列出IsolatedStorage中的所有文件和文件夾。

第一個應用程序使用庫類來創建新的文件夾/文件 我希望第二個應用程序列出由第一個應用程序創建的文件夾。 我如何讓他們使用相同的隔離存儲?

回答

4

使用IsolatedStorageFile.GetUserStoreForAssembly從庫中創建獨立存儲。

詳細here

你可以在你的庫使用下面的類型。應用程序1和應用程序2可以通過庫中的以下類型在相同的獨立存儲中寫入/讀取。

下圖:

public class UserSettingsManager 
    { 
     private IsolatedStorageFile isolatedStorage; 
     private readonly String applicationDirectory; 
     private readonly String settingsFilePath; 

     public UserSettingsManager() 
     { 
      this.isolatedStorage = IsolatedStorageFile.GetMachineStoreForAssembly(); 
      this.applicationDirectory = "UserSettingsDirectory"; 
      this.settingsFilePath = String.Format("{0}\\settings.xml", this.applicationDirectory); 
     } 

     public Boolean WriteSettingsData(String content) 
     { 
      if (this.isolatedStorage == null) 
      { 
       return false; 
      } 

      if (! this.isolatedStorage.DirectoryExists(this.applicationDirectory)) 
      { 
       this.isolatedStorage.CreateDirectory(this.applicationDirectory); 
      } 

      using (IsolatedStorageFileStream fileStream = 
       this.isolatedStorage.OpenFile(this.settingsFilePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)) 
      using (StreamWriter streamWriter = new StreamWriter(fileStream)) 
      { 

       streamWriter.Write(content); 
      } 

      return true; 
     } 

     public String GetSettingsData() 
     { 
      if (this.isolatedStorage == null) 
      { 
       return String.Empty; 
      } 

      using(IsolatedStorageFileStream fileStream = 
       this.isolatedStorage.OpenFile(this.settingsFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) 
      using(StreamReader streamReader = new StreamReader(fileStream)) 
      { 
       return streamReader.ReadToEnd(); 
      } 
     } 
    } 

編輯:

該DLL應該是一個強命名程序集。快照下方顯示如何爲組件添加強名稱。 Go to Project properties

In the Signing tab of the properties, Click on "New" drop down item and provide a snk name in the dialog

+0

嗨,我做錯了什麼。我已經創建了兩個WinForms,第二個將WriteSettingsData與您的代碼一起用於GetSettingsData和庫類。第一個工作正常,並創建新的文件夾與XML文件,但第二個不能讀取此文件夾我有錯誤:System.IO.DirectoryNotFoundException。我是否必須使用這些winform來使用相同的文件夾? – baranq 2011-05-29 17:22:55

+0

我看到,當我運行第二個winform時,它會在isolatedstorage中創建新文件夾(而不是使用與第一個winform相同的文件夾) – baranq 2011-05-29 18:15:08

+0

已添加我的代碼的dll應該是強命名的程序集。在我的答案中的編輯下查看附加的快照。 – 2011-05-30 06:15:41

相關問題