Skip to content

Instantly share code, notes, and snippets.

@Neferetheka
Created August 16, 2013 20:00
Show Gist options
  • Save Neferetheka/6253072 to your computer and use it in GitHub Desktop.
Save Neferetheka/6253072 to your computer and use it in GitHub Desktop.
Helper to manage Isolated Storage on Windows phone
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