5

我将东西保存在一个独立的存储文件中(使用类 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应用程序。

4

2 回答 2

4

当您实例化 IsolatedStorageFile 时,您是否将其范围限定为 IsolatedStorageScope.Machine?

好的,现在你已经说明了你的代码风格,我已经回去重新测试方法的行为,这里是解释:

  • GetMachineStoreForAssembly() - 范围为机器和程序集标识。同一应用程序中的不同程序集将具有自己的隔离存储。
  • GetMachineStoreForDomain() - 在我看来是用词不当。范围限定在程序集标识之上的机器和域标识。应该有一个仅适用于 AppDomain 的选项。
  • GetMachineStoreForApplication() - 这是你要找的。我已经对其进行了测试,不同的程序集可以获取写入另一个程序集的值。唯一的问题是,应用程序身份必须是可验证的。在本地运行时,无法正确确定,最终会出现“无法确定调用者的应用程序身份”异常。可以通过 Click Once 部署应用程序来验证。只有这样,这种方法才能应用并达到共享隔离存储的预期效果。
于 2008-09-16T14:14:44.100 回答
1

保存时调用 GetMachineStoreForDomain,但检索时调用 GetMachineStoreForAssembly。

GetMachineStoreForAssembly 的范围是代码正在执行的程序集,而 GetMachineStoreForDomain 的范围是当前运行的 AppDomain 和代码正在执行的程序集。只需将这些调用更改为 GetMachineStoreForApplication,它应该可以工作。

可以在http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile_members.aspx找到有关 IsolatedStorageFile 的文档

于 2008-09-16T15:11:55.850 回答