I created some code to read and write a byte array (byte[]) to and from isolated storage in my Xamarin Forms app. (Currently just UWP). When I write the file, the byte array should over 7000 bytes. When I read the file from isolated storage, I get 22 bytes and my file (an image file) will of course not display correctly.
Below is my code. Any suggestions would be greatly appreciated.
private byte[] ReadFromIsolatedStorage(string ps_FileName = "")
{
byte[] lobj_ReturnValue = null;
try
{
if (ps_FileName.Trim().Length == 0)
{
ps_FileName = "KioskIcon";
}
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
if (isoStore.FileExists(ps_FileName))
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(ps_FileName, FileMode.Open, isoStore))
{
lobj_ReturnValue = GetImageStreamAsBytes(isoStream);
}
}
}
catch (Exception ex)
{
App.ProcessException(ex);
}
return lobj_ReturnValue;
}
private byte[] GetImageStreamAsBytes(Stream input)
{
var buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
private void WriteToIsolatedStorage(byte[] pobj_ByteArray, string ps_FileName = "")
{
try
{
if (ps_FileName.Trim().Length == 0)
{
ps_FileName = "KioskIcon";
}
IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
if (isoStore.FileExists(ps_FileName))
{
isoStore.DeleteFile(ps_FileName);
}
Stream stream = new MemoryStream(pobj_ByteArray);
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(ps_FileName, FileMode.Create, isoStore))
{
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.Write(stream);
}
}
}
catch (Exception ex)
{
App.ProcessException(ex);
}
}
OK So I finally got it working. For anyone looking for exact working code, here it is.