WP7 Exception error - Operation not permitted on IsolatedStorageFileStream - c#

How do I solve the exception, Operation not permitted on IsolatedFileStream?
After debugging, I realised that a certain line wasn't read and it was skipped to the catch part. I am reading images from the photo samples in windows phone 7 as well as uploading them into skydrive. Can anybody guide me on how to solve this problem asap?
Thanks.
public BitmapImage fileName { get; set; }
private void GetImages()
{
MediaLibrary mediaLibrary = new MediaLibrary();
var pictures = mediaLibrary.Pictures;
foreach (var picture in pictures)
{
BitmapImage image = new BitmapImage();
image.SetSource(picture.GetImage());
MediaImage mediaImage = new MediaImage();
mediaImage.fileName = image;
UploadFile(mediaImage, picture.Name);
}
}
public void UploadFile(MediaImage image, string filepath)
{
if (skyDriveFolderID != string.Empty)
{
this.client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);
infoTextBlock.Text = "Uploading backup...";
dateTextBlock.Text = "";
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
// error occurs HERE
IsolatedStorageFileStream readStream = myIsolatedStorage.OpenFile(filepath, FileMode.Open, FileAccess.Read);
readStream.Close();
this.client.UploadAsync(skyDriveFolderID, filepath, true, readStream, null)
}
}

Are you sure error occurs there? I can se you are closing the stream before reading it. So it may be that you got the line of error wrong.
Also, are you absolutely sure, that file with that exact name exists in Isolated Storage?

Related

Byte[] from DB to BitmapImageSource -- One Error After Another

I am creating a UWP app for the company I work for part of the process is to upload an ID Photo. When the user clicks to upload a picker displays and it loads the image to an Image Element. This works fine, the issue is when the pull an existing record that has a photo attached already. The file is stored as a byte[], the code I use on .Net web apps does not work here. I can not get it to work even after a week of reading post after post on countless sites.
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
photo.ID = reader.GetGuid(0);
photo.AttachmentType = reader.GetString(1);
photo.AttachmentSize = reader.GetInt32(2);
photo.Attachment = (byte[])reader.GetValue(3);
}
}
RemoveBtn.Visibility = Visibility.Visible;
}
}
}
}
}
catch (Exception eSql)
{
var err = eSql.Message.ToString();
}
if (photo.Attachment != null && photo.Attachment.Length > 0)
{
//StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
//StorageFile file = await folder.CreateFileAsync($"tempImg{photo.AttachmentType}");
//string path = #"D:\DOT2";
//string fileName = "tempImg.png";
//string pathStr = Path.Combine(path, fileName);
using (Stream stream = new MemoryStream())
{
await stream.WriteAsync(photo.Attachment, 0, photo.Attachment.Length);
using (IRandomAccessStream fileStream = stream.AsRandomAccessStream())
{
BitmapImage img = new BitmapImage();
await img.SetSourceAsync(fileStream); //Error Occurs here.
CIPhoto.Source = img;
}
}
UploadBtn.Visibility = Visibility.Collapsed;
RemoveBtn.Visibility = Visibility.Visible;
}
The expected result is to convert the byte[] to a BitmapImageSource that i can set to an Image UI Element. I get error after error, currently i get an error saying : 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'. The commented section tells me that i am denied access. I am stuck, please help.

How to unzip a file in IsolatedStorage in windows phone 8 app?

Inside my app, I am trying to download about 180 small audio files all at once. I tried the BackgroundTransferService, but it does not seem stable with so many small files. So, now I am downloading a ZIP of all those audio and want extract them in "audio" folder. I tried the method in this thread:
How to unzip files in Windows Phone 8
But I get this error: 'System.IO.IOException' occurred in mscorlib.ni.dll... in the following code. How can I overcome this issue?
while (reader.ReadInt32() != 101010256)
{
reader.BaseStream.Seek(-5, SeekOrigin.Current); // this line causes error
}...
Also, where do I need to place this code and where do I give it the destination directory?
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(#"audio.rar", FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip())
{
string FileName = filename;
}
}
Use Silverlight SharpZipLib. Add SharpZipLib.WindowsPhone7.dll to your project (works on WP8 silverlight also).
private void Unzip()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
ZipEntry entry;
int size;
byte[] data = new byte[2048];
using (ZipInputStream zip = new ZipInputStream(store.OpenFile("YourZipFile.zip", FileMode.Open)))
{
// retrieve each file/folder
while ((entry = zip.GetNextEntry()) != null)
{
if (!entry.IsFile)
continue;
// if file name is music/rock/new.mp3, we need only new.mp3
// also you must make sure file name doesn't have unsupported chars like /,\,etc.
int index = entry.Name.LastIndexOf('/');
string name = entry.Name.Substring(index + 1);
// create file in isolated storage
using (var writer = store.OpenFile(name, FileMode.Create))
{
while (true)
{
size = zip.Read(data, 0, data.Length);
if (size > 0)
writer.Write(data, 0, size);
else
break;
}
}
}
}
}
}
There are several 3rd party libraries in order to extract ZIP files in WP8 like the ZipLib which you can download from # http://slsharpziplib.codeplex.com/
however DotNetZip a parent ZipLib and much more stable.
Here is a sample code. Not checked if it works, but this is how you go at it.
ZipFile zip = ZipFile.Read(ZipFileToUnzip);
foreach (ZipEntry ent in zip)
{
ent.Extract(DirectoryWhereToUnizp, ExtractExistingFileAction.OverwriteSilently);
}
I have just solved this. what you can do is use this method and your file will go save to isolated storage in proper folder structure as present in your zip file. you can change according to your need where you want to store the data.
I have just read a sample.zip file. From your app folder.
private async Task UnZipFile()
{
var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (var fileStream = Application.GetResourceStream(new Uri("sample.zip", UriKind.Relative)).Stream)
{
var unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip)
{
if (!string.IsNullOrEmpty(filename))
{
if (filename.Any(m => m.Equals('/')))
{
myIsolatedStorage.CreateDirectory(filename.Substring(0, filename.LastIndexOfAny(new char[] { '/' })));
}
//save file entry to storage
using (var streamWriter =
new StreamWriter(new IsolatedStorageFileStream(filename,
FileMode.Create,
FileAccess.ReadWrite,
myIsolatedStorage)))
{
streamWriter.Write(unzip.GetFileStream(filename));
}
}
}
}
}
cheers :)

wp8 Operation not permitted on IsolatedStorageFileStream

I am copying all images from my device to directory. While copying the images I am getting this error Operation not permitted on IsolatedStorageFileStream.
Here is my code to copy the files.
MediaLibrary m = new MediaLibrary();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.DirectoryExists("ImagesZipFolder"))
{
deleteFileFolder("ImagesZipFolder");
}
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
foreach (var picture in m.Pictures)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder/" + picture.Name, FileMode.CreateNew, store))
{
BitmapImage image = new BitmapImage();
image.SetSource(picture.GetImage());
byte[] bytes = ConvertToBytes(image);
stream.Write(bytes, 0, bytes.Length);
}
}
}
}
Here is my ConvertToBytes method.
public byte[] ConvertToBytes(BitmapImage bitmapImage)
{
byte[] data = null;
WriteableBitmap wBitmap = null;
using (MemoryStream stream = new MemoryStream())
{
wBitmap = new WriteableBitmap(bitmapImage);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
//data = stream.GetBuffer();
data = stream.ToArray();
DisposeImage(bitmapImage);
return data;
}
}
Basically what I am trying is to create a zip file of all images. I have total 222 images in my device. So how can I solve this issue ? How can I create a zip of this images?
Most probably this is due to the concurrent access to the file
you can refer to the link:
Operation not permitted on IsolatedStorageFileStream. error
I checked your code and it seems to be working (providing there's no error in DisposeImage() method) There is no OperationNotPermittedException occuring. However, if there is error in your code, then it can only be because of deleteFileFolder("ImagesZipFolder") line. Can you give me the snippet so that I can study it further. I m posting the working code... I have replaced that method with simple predefined one--
MediaLibrary m = new MediaLibrary();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.DirectoryExists("ImagesZipFolder"))
{
store.DeleteDirectory("ImagesZipFolder");
}
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
foreach (var picture in m.Pictures)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder/" + picture.Name, FileMode.CreateNew, store))
{
BitmapImage image = new BitmapImage();
image.SetSource(picture.GetImage());
byte[] bytes = ConvertToBytes(image);
stream.Write(bytes, 0, bytes.Length);
}
}
}
}

How to store and get images in IsolatedStorage?

I want to be able to save images in IsolatedStorage, and later get it.
for this purpose I wrote a helper which I want to access it from everywhere in my app:
for creating an image:
public static void SaveImage(Stream image, string name)
{
try
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (!isolatedStorage.DirectoryExists("MyImages"))
{
isolatedStorage.CreateDirectory("MyImages");
}
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, isolatedStorage))
{
StreamWriter sw = new StreamWriter(fileStream);
sw.Write(image);
sw.Close();
}
}
catch (Exception ex)
{
throw new Exception("failed");
}
}
and for getting that image again:
public static BitmapImage Get(string name)
{
try
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Open, isolatedStorage))
{
BitmapImage image = new BitmapImage();
image.SetSource(fileStream);
return image;
}
}
catch (Exception ex)
{
throw new Exception("failed");
}
}
The problem appears when I try to set source of image I get this error message:
The component cannot be found. (Exception from HRESULT: 0x88982F50)
Assuming you have the right Capabilities under your WMAppManifest.xml what you need is:
public static void SaveImage(Stream image, string name)
{
var bitmap = new BitmapImage();
bitmap.SetSource(attachmentStream);
var wb = new WriteableBitmap(bitmap);
var temp = new MemoryStream();
wb.SaveJpeg(temp, wb.PixelWidth, wb.PixelHeight, 0, 50);
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!myIsolatedStorage.DirectoryExists("MyImages"))
{
myIsolatedStorage.CreateDirectory("MyImages");
}
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, myIsolatedStorage))
{
fileStream.Write(((MemoryStream)temp).ToArray(), 0, ((MemoryStream)temp).ToArray().Length);
fileStream.Close();
}
}
}
That should work and store your image as a jpeg into your desired directory. if it doesn't, make sure that the create directory and Path.Combine() methods are being used correctly.

LockScreen for windows phone 8

Hi I am developing a lockscreen app where I am using listbox of images.After selecting a image when i am clicking a button to set lockscreen,It should updated.But it bot updating .Here is my code
private async void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
MediaLibrary mediaLibrary = new MediaLibrary();
//ImageSource im = image1.Source;
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(mediaLibrary.Pictures[imageList.SelectedIndex].GetImage());
String tempJPEG = "MyWallpaper1.jpg";
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
StreamResourceInfo sri = null;
Uri uri = new Uri(tempJPEG, UriKind.Relative);
sri = Application.GetResourceStream(uri);
WriteableBitmap wb = new WriteableBitmap(bitmap);
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 90);
fileStream.Close();
}
LockScreenChange(tempJPEG);
}
private async void LockScreenChange(string filePathOfTheImage)
{
if (!LockScreenManager.IsProvidedByCurrentApplication)
{
await LockScreenManager.RequestAccessAsync();
}
if (LockScreenManager.IsProvidedByCurrentApplication)
{
var schema = "ms-appdata:///Local/";
var uri = new Uri(schema + filePathOfTheImage, UriKind.Absolute);
LockScreen.SetImageUri(uri);
var currentImage = LockScreen.GetImageUri();
MessageBox.Show("Success", "LockScreen changed", MessageBoxButton.OK);
}
else
{
MessageBox.Show("Background cant be changed. Please check your permissions to this application.");
}
}
Actually when first time the app is launched and when I am clicking set button,the current selected image is set as lockscreen,after that when i am selecting another image,it is showing lockscreen changed ,success.No error and no exception.I dont know where is the problem.
Please help........
It got solved by changing temporary file name to original file name i.e. string tempJpeg

Categories

Resources