Thursday, November 29, 2012

Copy Windows Phone Content To Isolated Storage

Some times a database is deployed with the application as a content file.

However, the database can't be used directly, it must be copied to the storage first.

In this sample code, the content file is copied to the isolated storage if it isn't copied yet.
IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication();
String DBFile = "DB.sqlite";
if (!ISF.FileExists(DBFile)) CopyFromContentToStorage(ISF, "Database/DB.sqlite", DBFile);

private void CopyFromContentToStorage(IsolatedStorageFile ISF, String SourceFile, String DestinationFile)
    Stream Stream = Application.GetResourceStream(new Uri(SourceFile, UriKind.Relative)).Stream;
    IsolatedStorageFileStream ISFS = new IsolatedStorageFileStream(DestinationFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, ISF);
    CopyStream(Stream, ISFS);
private void CopyStream(Stream Input, IsolatedStorageFileStream Output)
    Byte[] Buffer = new Byte[5120];
    Int32 ReadCount = Input.Read(Buffer, 0, Buffer.Length);
    while (ReadCount > 0)
        Output.Write(Buffer, 0, ReadCount);
        ReadCount = Input.Read(Buffer, 0, Buffer.Length);
The code assumes that the file to be copied is named 'DB.sqlite' that resides in a folder named 'database' and was added to the project as a content file.

No comments:

Post a Comment