/// <summary>
/// Sample code for loading image from IsolatedStorage
/// </summary>
private object LoadImageFromIsolatedStorage(string strImageName)
{
// The image will be read from isolated storage into the following byte array
byte[] data;
// Read the entire image in one go into a byte array
try
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
// Open the file - error handling omitted for brevity
// Note: If the image does not exist in isolated storage the following exception will be generated:
// System.IO.IsolatedStorage.IsolatedStorageException was unhandled
// Message=Operation not permitted on IsolatedStorageFileStream
string fileName="/Images/"+strImageName;
if (!isf.FileExists(fileName)) return null;
using (IsolatedStorageFileStream isfs =isf.OpenFile(fileName, FileMode.Open, FileAccess.Read))
{
// Allocate an array large enough for the entire file
data = new byte[isfs.Length];
// Read the entire file and then close it
isfs.Read(data, 0, data.Length);
isfs.Close();
}
}
// Create memory stream and bitmap
MemoryStream ms = new MemoryStream(data);
BitmapImage bi = new BitmapImage();
// Set bitmap source to memory stream
bi.SetSource(ms);
return bi;
}
catch (Exception e)
{
// handle the exception
Debug.WriteLine(e.Message);
return null;
}
}
关键点先判断文件是否存在,如果不存在则直接返回,避免不必要的文件读写。
评论