如何在 C# 控制台应用程序中使用 IsolatedStorage

How to use IsolatedStorage in a C# Console Application

我有一个使用 OpenXml 生成电子表格文档的控制台应用程序。

我正在尝试使用 IsolatedStorage,如下面的代码所示,但出现错误消息:

Unable to determine application identity of the caller?

这是我的做法:

    var store = IsolatedStorageFile.GetUserStoreForApplication();

    IsolatedStorageFileStream rootFile = store.CreateFile(src);
    store.CreateDirectory(tgt);

        var doc = SpreadsheetDocument.Create(rootFile, SpreadsheetDocumentType.Workbook, false);

        WorkbookPart workbookpart = doc.AddWorkbookPart();
        workbookpart.Workbook = new Workbook();

        Sheets sheets = doc.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

        return doc;

我试过这样做:

if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
{
 // above code is here
}

但同样没有定义 DesignerProperties,我认为这是因为它是一个 ConsoleApp 而不是 MVC 或其他基于 UI 的系统。

非常感谢。

这很简单。根据 MSDN:

All assemblies associated with an application use the same isolated store when using this method. This method can be used only when the application identity can be determined - for example, when the application is published through ClickOnce deployment or is a Silverlight-based application. If you attempt to use this method outside a ClickOnce or Silverlight-based application, you will receive an IsolatedStorageException exception, because the application identity of the caller cannot be determined.

您不能使用 GetUserStoreForApplication,因为您的应用程序不是由其 URL 定义的,Silverlight 和 ClickOnce 应用程序就是这种情况。通常的控制台应用程序没有可用于这种情况的应用程序标识。

处理此问题的一种方法是使用不同的独立存储,例如:

IsolatedStorageFile.GetStore
(
 IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, 
 null, null
);

它也有助于使用强命名程序集 - 为每个程序集提供适当的唯一标识。