使用隔离存储时"找不到文件"
时间:2020-03-05 18:56:02 来源:igfitidea点击:
我将东西保存在隔离存储文件中(使用类IsolatedStorageFile)。它运作良好,当我从GUI层调用DAL层中的保存和检索方法时,可以检索保存的值。但是,当我尝试从同一项目中的另一个程序集检索相同的设置时,它给了我FileNotFoundException。我做错了什么?这是一般概念:
public void Save(int number) { IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly(); IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, storage); StreamWriter writer = new StreamWriter(fileStream); writer.WriteLine(number); writer.Close(); } public int Retrieve() { IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly(); IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.Open, storage); StreamReader reader = new StreamReader(fileStream); int number; try { string line = reader.ReadLine(); number = int.Parse(line); } finally { reader.Close(); } return number; }
我尝试使用所有GetMachineStoreFor *范围。
编辑:由于我需要几个程序集来访问文件,因此,除非是ClickOnce应用程序,否则似乎不可能使用隔离存储。
解决方案
回答
实例化IsolatedStorageFile时,是否将其范围限制为IsolatedStorageScope.Machine?
好了,现在我们已经说明了代码风格,并且我回到了重新测试方法的行为的地方,这里是解释:
- GetMachineStoreForAssembly()-范围限于机器和程序集标识。同一应用程序中的不同程序集将具有自己的隔离存储。
- GetMachineStoreForDomain()-我认为是一个不当用语。范围仅限于计算机,而域标识位于程序集标识之上。应该只为AppDomain提供一个选项。
- GetMachineStoreForApplication()-这是我们要寻找的。我已经对其进行了测试,并且不同的程序集可以获取在另一个程序集中编写的值。唯一的问题是,应用程序身份必须是可验证的。在本地运行时,无法正确确定它,并且最终将出现异常"无法确定调用者的应用程序身份"。可以通过单击一次部署应用程序来进行验证。只有这样,该方法才能应用并达到共享隔离存储的预期效果。
回答
保存时,我们正在调用GetMachineStoreForDomain,但是检索时,我们正在调用GetMachineStoreForAssembly。
GetMachineStoreForAssembly的范围是执行代码的程序集,而GetMachineStoreForDomain的范围是当前运行的AppDomain和执行代码的程序集。只需将这些调用更改为GetMachineStoreForApplication,它就可以工作。
可以在http://msdn.microsoft.com/zh-cn/library/system.io.isolatedstorage.isolatedstoragefile_members.aspx中找到IsolatedStorageFile的文档。