Search code examples
c#c#-4.0openxmlisolatedstorageisolatedstoragefile

How to use IsolatedStorage in a C# Console Application


I have a console application which uses an OpenXml to generate spreadsheet documents.

I am trying to use IsolatedStorage as shown in the code below but it is erroring with a message of:

Unable to determine application identity of the caller?

Here is how I am doing it:

    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;

I tried to do something like this:

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

But again the DesignerProperties wasn't defined, I think this is because it is a ConsoleApp rather than an MVC or other UI based system.

Many thanks.


Solution

  • This is pretty straight-forward. As per 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.

    You can't use GetUserStoreForApplication, because your application is not defined by its URL, as is the case with Silverlight and ClickOnce applications. The usual console application has no application identity to use for such a scenario.

    One way to handle this would be by using a different isolated storage, for example:

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

    It helps to use strong named assemblies too - that provides a suitably unique identification of each assembly.