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.
Related
I have seen numerous similar questions and I have really tried all the solutions but none seems to work for me.
This is what I have now:
private readonly object _lock = new object();
List<DataModel> dataList = new List<DataModel>();
lock (_lock)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("Data.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<DataModel>));
dataList = (List<DataModel>)serializer.Deserialize(stream);
}
}
catch (IsolatedStorageException e) { e.ToString(); }
}
}
The error occurs on the line using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("Data.xml", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)).
I deduced from the other solutions that I read that this error mainly occurs when I want to write to the file while others are reading it or execute that code block several times concurrently, I end up locking the file."
With the presence of the lock, FileAccess.ReadWrite and FileShare.ReadWrite statements, I'm pretty sure something else is throwing that exception.
My question is what could be throwing the exception (IsolatedStorageException) and how do I take care of it?
There is no InnerException on this one.
Edit: Upon Kookiz suggestion, I'm including this code lines
First, I create my .xml file like this:
public static void createDataXML()
{
List<DataModel> dataList = new List<DataModel>();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists("Data.xml"))
{ return; }
using (IsolatedStorageFileStream stream = myIsolatedStorage.CreateFile("Data.xml"))
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(List<DataModel>));
serializer.Serialize(stream, dataList);
}
catch
{ }
}
}
}
Later, I populate with this code:
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("Data.xml", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<DataModel>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, dataList);
}
}
}
I know this is a less conventional way of doing this but it IS a way. I was attempting to do something else and this was the result. Just add in the known type you need and this will work
[DataContractAttribute]
[KnownType (typeof(List<String>))]
public class SerializableObject
{
[DataMember]
public List<String> serFile { get; set; }
}
public static Object GetFile(String FileName)
{
try
{
if (!IsolatedStorageFile.GetUserStoreForApplication().FileExists(FileName))
{
throw new System.ArgumentException("File Doesn't Exist In Isoloated Storage");
}
}
catch { return null; }
Object ret = new Object();
try
{
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(#"\" + FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
SerializableObject serList = new SerializableObject();
DataContractSerializer dsc = new DataContractSerializer(serList.GetType());
ret = ((SerializableObject)dsc.ReadObject(fileStream)).serFile;
}
catch (Exception error) { throw new System.ArgumentException(error.Message); }
return ret;
}
The implied task here is that you need to serialize it within a SerializableObject instance. Let me know if you need that code also
Edit
As promised, the savefile function
public static void SaveFile(String FileName, List<String> File)
{
try
{
if (FileName.Length < 1)
{
throw new System.ArgumentException("File Name Must Not Be Empty");
}
if (IsolatedStorageFile.GetUserStoreForApplication().AvailableFreeSpace <= 0)
{
throw new System.ArgumentException("Isolated Storage Out of Memory - Please free up space.");
}
if (IsolatedStorageFile.GetUserStoreForApplication().FileExists(FileName))
{
throw new System.ArgumentException("File Already Exists - Please choose a unique name.");
}
if (File == null)
{
throw new System.ArgumentException("Cannot Save Null Files");
}
}
catch (Exception e)
{
return;
}
try
{
SerializableObject so = new SerializableObject() { serFile = File };
DataContractSerializer dsc = new DataContractSerializer(so.GetType());
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writer;
writer = new StreamWriter(new IsolatedStorageFileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, file));
dsc.WriteObject(writer.BaseStream, so);
}
catch (Exception error) { throw new System.ArgumentException(error.Message); }
}
Enjoy serializing!
My dear, though this exception of Operation Not Permitted On IsolatedStorage is mainly due to ReadWrite by another thread, in your case it is because of ONE SIMPLE REASON
FileMode.Open throws exception when the filename DOES NOT EXIST
Try with FileMode.OpenOrCreate and it will work like a charm
List<DataModel> dataList = new List<DataModel>();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("Data.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<DataModel>));
dataList = (List<DataModel>)serializer.Deserialize(stream);
}
}
I want to upload my recorded file to skydrive and I am using these codes
For recording;
void StopRecording()
{
// Get the last partial buffer
int sampleSize = microphone.GetSampleSizeInBytes(microphone.BufferDuration);
byte[] extraBuffer = new byte[sampleSize];
int extraBytes = microphone.GetData(extraBuffer);
// Stop recording
microphone.Stop();
// Create MemoInfo object and add at top of collection
int totalSize = memoBufferCollection.Count * sampleSize + extraBytes;
TimeSpan duration = microphone.GetSampleDuration(totalSize);
MemoInfo memoInfo = new MemoInfo(DateTime.UtcNow, totalSize, duration);
memoFiles.Insert(0, memoInfo);
// Save data in isolated storage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storage.CreateFile("/shared/transfers/" + memoInfo.FileName))
{
// Write buffers from collection
foreach (byte[] buffer in memoBufferCollection)
stream.Write(buffer, 0, buffer.Length);
// Write partial buffer
stream.Write(extraBuffer, 0, extraBytes);
}
}
}
For Uploading file;
async void OnSaveButtonClick(object sender, RoutedEventArgs args)
{
Button btn = sender as Button;
MemoInfo clickedMemoInfo = btn.Tag as MemoInfo;
memosListBox.SelectedItem = clickedMemoInfo;
if (this.client == null)
{
gridSingin.Visibility = Visibility.Visible;
memosListBox.Visibility = Visibility.Collapsed;
}
else
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fileStream = store.OpenFile(clickedMemoInfo.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
LiveOperationResult res = await client.BackgroundUploadAsync("me/skydrive",
new Uri("/shared/transfers/" + clickedMemoInfo.FileName, UriKind.Relative),
OverwriteOption.Overwrite
);
InfoText.Text = "File " + clickedMemoInfo.FileName + " uploaded";
}
}
}
}
But I am gettin error in here
LiveOperationResult res = await client.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + clickedMemoInfo.FileName, UriKind.Relative), OverwriteOption.Overwrite);
I am getting this error;
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in System.Windows.ni.dll
Could you help me, please?
You cannot have the file open when trying to upload. Try doing this.
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(fileName))
{
client.BackgroundUploadAsync("me/skydrive", new Uri(fileName, UriKind.Relative),
OverwriteOption.Overwrite);
}
}
When I run
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
myStore.CopyTextFile("HTDocs\\help.html", true);
I have error: "Operation not permitted on IsolatedStorageFileStream." It's from tutorial. How should I fix that?
public static class ISExtensions
{
public static void CopyTextFile(this IsolatedStorageFile isf, string filename, bool replace = false)
{
if (!isf.FileExists(filename) || replace == true)
{
StreamReader stream = new StreamReader(TitleContainer.OpenStream(filename));
IsolatedStorageFileStream outFile = isf.CreateFile(filename);
//
//
string fileAsString = stream.ReadToEnd();
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(fileAsString);
outFile.Write(fileBytes, 0, fileBytes.Length);
stream.Close();
outFile.Close();
}
}
}
Try something like this:
// isolated storage
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
// access to resource files
StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri(#"HTDocs\help.html", UriKind.Relative));
using (Stream origFileStream = streamInfo.Stream)
{
// open the filestream for the isostorage file and copy the content from the original stream
using (IsolatedStorageFileStream fileStream = myStore.CreateFile("help.html"))
{
origFileStream.CopyTo(fileStream);
origFileStream.Close();
}
}
Im trying to get Images from URL and store it within my isolated storage, and then get the images from the isolated storage
here is my relevant code:
public void GetImages()
{
string uri = "http://sherutnetphpapi.cloudapp.net/mini_logos/" + path;
WebClient m_webClient = new WebClient();
imageUri = new Uri(uri);
m_webClient.OpenReadAsync(imageUri);
m_webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_ImageOpenReadCompleted);
m_webClient.AllowReadStreamBuffering = true;
}
void webClient_ImageOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
string iso_path = "~/SherutApp1;component/" + path;
var isolatedfile = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(iso_path, FileMode.Create, isolatedfile))
{
byte[] buffer = new byte[e.Result.Length];
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}
}
}
i get the exception at the headline on this line:
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(iso_path, FileMode.Create, isolatedfile))
I don't know what is the problem, although i think that maybe images does not inserted correctly to the isolated storage.
I don't think you need the "~/SherutApp1;component/" part in there. If you the entire path is "test.jpg" or "folderThatExists\\test.jpg" it should work.
I am looking to create a function that takes a BitmapImage and saves it as a JPEG on the local Windows Phone 7 device in isolated storage:
static public void saveImageLocally(string barcode, BitmapImage anImage)
{
// save anImage as a JPEG on the device here
}
How do I accomplish this? I'm assuming I used IsolatedStorageFile somehow?
Thanks.
EDIT:
Here is what I have found so far... can anyone confirm if this is the correct way to do this?
static public void saveImageLocally(string barcode, BitmapImage anImage)
{
WriteableBitmap wb = new WriteableBitmap(anImage);
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fs = isf.CreateFile(barcode + ".jpg"))
{
wb.SaveJpeg(fs, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
}
}
static public void deleteImageLocally(string barcode)
{
using (IsolatedStorageFile MyStore = IsolatedStorageFile.GetUserStoreForApplication())
{
MyStore.DeleteFile(barcode + ".jpg");
}
}
static public BitmapImage getImageWithBarcode(string barcode)
{
BitmapImage bi = new BitmapImage();
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fs = isf.OpenFile(barcode + ".jpg", FileMode.Open))
{
bi.SetSource(fs);
}
}
return bi;
}
To save it:
var bmp = new WriteableBitmap(bitmapImage);
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storage.CreateFile(#"MyFolder\file.jpg"))
{
bmp.SaveJpeg(stream, 200, 100, 0, 95);
stream.Close();
}
}
Yes, the stuff you added in your edit is exactly what I have done before :) it works.
This is my code but you can take the neccesary points from there:
var fileName = String.Format("{0:}.jpg", DateTime.Now.Ticks);
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap(480, 552);
bmpCurrentScreenImage.Render(yourCanvas, new MatrixTransform());
bmpCurrentScreenImage.Invalidate();
SaveToMediaLibrary(bmpCurrentScreenImage, fileName, 100);
public void SaveToMediaLibrary(WriteableBitmap bitmap, string name, int quality)
{
using (var stream = new MemoryStream())
{
// Save the picture to the Windows Phone media library.
bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, quality);
stream.Seek(0, SeekOrigin.Begin);
new MediaLibrary().SavePicture(name, stream);
}
}