Created
August 16, 2013 20:00
-
-
Save Neferetheka/6253072 to your computer and use it in GitHub Desktop.
Helper to manage Isolated Storage on Windows phone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.IO.IsolatedStorage; | |
namespace Tools | |
{ | |
public abstract class ISHelper | |
{ | |
private const string directory = "Storage"; | |
/// <summary> | |
/// Check if an item exists in storage | |
/// </summary> | |
/// <param name="key">key for data</param> | |
/// <returns>true if it exists. false otherwise</returns> | |
public static bool HasItem(string key) | |
{ | |
using (var store = IsolatedStorageFile.GetUserStoreForApplication()) | |
{ | |
return store.FileExists(Path.Combine(directory, key)); | |
} | |
} | |
/// <summary> | |
/// Get an item from the storage | |
/// </summary> | |
/// <param name="key">key for data</param> | |
/// <returns>Null if empty. Data as string otherwise</returns> | |
public static string GetItem(string key) | |
{ | |
try | |
{ | |
using (var store = IsolatedStorageFile.GetUserStoreForApplication()) | |
{ | |
string filePath = Path.Combine(directory, key); | |
if (store.FileExists(filePath)) | |
{ | |
using (StreamReader reader = new StreamReader(store.OpenFile(filePath, FileMode.Open, FileAccess.Read))) | |
{ | |
return reader.ReadToEnd(); | |
} | |
} | |
else | |
return null; | |
} | |
} | |
catch | |
{ | |
return null; | |
} | |
} | |
/// <summary> | |
/// Put data in storage | |
/// </summary> | |
/// <param name="key">key of data</param> | |
/// <param name="value">value to put in storage as string</param> | |
/// <returns>true if okay, false otherwise</returns> | |
public static bool SetItem(string key, string value) | |
{ | |
try | |
{ | |
using (var store = IsolatedStorageFile.GetUserStoreForApplication()) | |
{ | |
if (!store.DirectoryExists(directory)) | |
store.CreateDirectory(directory); | |
string filePath = Path.Combine(directory, key); | |
if (store.FileExists(filePath)) | |
{ | |
store.DeleteFile(filePath); | |
} | |
using (var isoFileStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate, store)) | |
{ | |
using (var isoFileWriter = new StreamWriter(isoFileStream)) | |
{ | |
isoFileWriter.WriteLine(value); | |
} | |
} | |
return true; | |
} | |
} | |
catch | |
{ | |
return false; | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment