Question

I am developing silverlight web part by using the client object model. I am getting the bitmap image from sharepoint server. Now I want to save this bitmap image in isolated storage. So I am using following code

 WriteableBitmap wb = new WriteableBitmap(attachments);

 using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
 {
     using (IsolatedStorageFileStream isoStream =
     new IsolatedStorageFileStream("abcd1.jpg", FileMode.Create, isoFile))
     {
         using (StreamWriter sw = new StreamWriter(isoStream))
         {
             sw.Write(wb.ToByteArray());
         }
     }
 }

Now I am seeing the saved image at location C:\Users\Rent2\AppData\LocalLow\Microsoft\Silverlight\is\vzvpufsm.s4i\m0laonzr.til\1\s\nkhajster01es5wdoyfxd0n5rd2dls3ovyu4wcdig04zjx44hyaaafea\f

When I click on it, it gives me message as "Invalid Image". Can you please tell me how should i write code so that I can see the actual image after saving it in isolated storage ?

Was it helpful?

Solution

    private void zipFile()
            {     
                context = Microsoft.SharePoint.Client.ClientContext.Current;
                Microsoft.SharePoint.Client.File.OpenBinaryDirect(
                        context,
                        @"/TemplateInvoice/" + App.templateFileName + ".xlsx", successFile, FailFile);                  
            }

    private void successFile(object sender, OpenBinarySucceededEventArgs args)
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    // Obtain the isolated storage for an application.
                    try
                    {
                        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            Stream strm = args.Stream;

                            using (var isoStream = store.OpenFile(App.templateFileName + ".zip", FileMode.OpenOrCreate))
                            {
                                // Read the resource file into a byte array.
                                bytes = new byte[strm.Length];
                                int numBytesToRead = (int)strm.Length;
                                int numBytesRead = 0;
                                while (numBytesToRead > 0)
                                {
                                    // Read may return anything from 0 to numBytesToRead.
                                    int n = strm.Read(bytes, numBytesRead, numBytesToRead);
                                    // The end of the file is reached.
                                    if (n == 0)
                                        break;
                                    numBytesRead += n;
                                    numBytesToRead -= n;
                                }


                                numBytesToRead = bytes.Length;

                                // Write the byte array to the IsolatedStorageFileStream.
                                isoStream.Write(bytes, 0, numBytesToRead);
                                //isoStream.Dispose();
                            }

                            strm.Close();

                            string path = App.templateFileName + ".zip";
                            ZipHelp.UnZip(path, System.IO.Path.GetDirectoryName(path), 4096);

                            replaceFileContent();

                            string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(path);
                            string fileName = ZipHelp.Zip(rootDirectory.Replace(".zip", ""), invoice);

                            //string filename = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "Invoice1.xlsx";

                            // Read the resource file into a byte array.
                            using (var stream = store.OpenFile(fileName, FileMode.Open))
                            {

                                bytes = new byte[stream.Length];
                                int numBytesToRead = (int)stream.Length;
                                int numBytesRead = 0;
                                while (numBytesToRead > 0)
                                {
                                    // Read may return anything from 0 to numBytesToRead.
                                    int n = stream.Read(bytes, numBytesRead, numBytesToRead);
                                    // The end of the file is reached.
                                    if (n == 0)
                                        break;
                                    numBytesRead += n;
                                    numBytesToRead -= n;
                                }


                                InvoiceTemplete invoiceTemplate = new InvoiceTemplete(fileName, bytes, SetMessage);
                                invoiceTemplate.AddDocument(invoiceTemplate);
                            }

                        }

                        //mark rows as billed
                        foreach (var item in PrivatePayList)
                        {
                            MedwaiverViewModel MedwaiverViewModelObj = new MedwaiverViewModel();
                            MedwaiverViewModelObj.ChangeBillingStatus(item.ListItemId, "Billed");

                            if (MedwaiverTimeLogList != null)
                            {
                                MedwaiverTimeLogList.Remove(item);
                            }

                            if (ClientSpecificTimeLogList != null)
                            {
                                ClientSpecificTimeLogList.Remove(item);
                            }

                            if (rangeBoundTimeLogListForDate != null)
                            {
                                rangeBoundTimeLogListForDate.Remove(item);
                            }

                            if (vRangeBoundTimeLogListForDateAndClient != null)
                            {
                                vRangeBoundTimeLogListForDateAndClient.Remove(item);
                            }

                        }

                    }
                    catch (IsolatedStorageException isx)
                    {
                        MessageBox.Show(isx.Message);
                    }
                });
            }

     private void FailFile(object sender, OpenBinaryFailedEventArgs e)
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Fail");
                });
            }


//The following class zip and unzip the file

class ZipHelp
    {
        static List<string> folderPathList = new List<string>();      

        public static string Zip(string rootDirectory, string fileName)
        {
            byte[] buffer;

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream zipFileStream = store.CreateFile(fileName + ".xlsx");
                ZipOutputStream zipOutStream = new ZipOutputStream(zipFileStream);
                zipOutStream.UseZip64 = UseZip64.Off;
                //zipOutStream.CanPatchEntries

                foreach (var item in folderPathList)
                {
                    string entryName = "";

                    buffer = new byte[4096];

                    if (item.Substring(0,1) == @"/")
                    {
                        //removes leading /
                        entryName = item.Substring(1);
                    }
                    else
                    {
                        entryName = item;
                    }

                    ZipEntry entry = new ZipEntry(entryName);
                    //entry.CompressionMethod = CompressionMethod.Deflated;
                    //entry.
                    entry.IsZip64Forced();
                    //entry.IsDirectory



                    zipOutStream.PutNextEntry(entry);


                    using (IsolatedStorageFileStream stream = store.OpenFile(rootDirectory + @"\" + item, FileMode.Open))
                    {


int size;
                        do
                        {
                            size = stream.Read(buffer, 0, buffer.Length);
                            zipOutStream.Write(buffer, 0, size);
                        } while (size > 0);

                    stream.Close();
                }
            }

            zipOutStream.Close();
            zipFileStream.Close();
        }

        return fileName + ".xlsx";


        //string[] directories = GetLocationTypes();

        //zip();

        //string[] filenames = Directory.GetFiles(directories);

        //using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        //{                
        //    using (var isoStream = store.OpenFile("@" + rootDirectory, FileMode.OpenOrCreate))
        //    {
        //        //foreach(string dir in 
        //    }
        //}
    }       

    private static string[] GetLocationTypes()
    {
        using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        {
            return store.GetDirectoryNames();
        }

    }

    /// <summary>
    /// UnZip a file
    /// </summary>
    /// <param name="SrcFile">source file path</param>
    /// <param name="DstFile">unzipped file path</param>
    /// <param name="BufferSize">buffer to use</param>
    public static void UnZip(string SrcFile, string DstFile, int BufferSize)
    {
        folderPathList.Clear();

        IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
        FileStream fileStreamIn = store.OpenFile(SrcFile, FileMode.Open, FileAccess.Read);

        ZipInputStream zipInStream = new ZipInputStream(fileStreamIn);
        string rootDirectory = System.Windows.Browser.HttpUtility.UrlDecode(SrcFile);
        rootDirectory = rootDirectory.Replace(".zip", "");
        store.CreateDirectory(rootDirectory);

        while (true)
        {
            ZipEntry entry = zipInStream.GetNextEntry();

            if (entry == null)
                break;

            if (entry.Name.Contains("/"))
            {
                string[] folders = entry.Name.Split('/');

                string lastElement = folders[folders.Length - 1];
                var folderList = new List<string>(folders);
                folderList.RemoveAt(folders.Length - 1);
                folders = folderList.ToArray();

                string folderPath = "";
                foreach (string str in folders)
                {
                    folderPath = folderPath + "/" + str;
                    if (!store.DirectoryExists(rootDirectory + "/" + folderPath))
                    {
                        store.CreateDirectory(rootDirectory + "/" + folderPath);
                    }
                }

                folderPath = folderPath + "/" + lastElement;
                writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, folderPath);

            }
            else
            {
                writeToFile(BufferSize, fileStreamIn, zipInStream, rootDirectory, entry.Name);
            }

        }

        zipInStream.Close();
        fileStreamIn.Close();

    }

    private static void writeToFile(int BufferSize, FileStream fileStreamIn, ZipInputStream zipInStream, string rootDirectory, string folderPath)
    {
        IsolatedStorageFile store1 = IsolatedStorageFile.GetUserStoreForApplication();
        FileStream fileStreamOut = store1.OpenFile(rootDirectory + "/" + folderPath, FileMode.Create, FileAccess.Write);

        folderPathList.Add(folderPath);

        int size;
        byte[] buffer = new byte[BufferSize];
        do
        {
            size = zipInStream.Read(buffer, 0, buffer.Length);
            fileStreamOut.Write(buffer, 0, size);
        } while (size > 0);


        fileStreamOut.Close();

    }
}

OTHER TIPS

I can think of two viable options here.

  1. In your code above, save off the Pixels array of the WriteableBitmap. Then to restore it, you would create a WriteableBitmap of the appropriate size and the set the Pixels array to the stored data.

-or-

  1. Use a HttpWebRequest or WebClient request to get the raw image stream and save that to IsolatedStorage.

There are pros and cons to each of these, in the first case the data is uncompressed and will take up more space in isolated storage and you would not be able to open the image from disk outside of Silverlight, similar to the issue you had above. For the second option you can run into cross domain issues if the images are on a different server than your Silverlight XAP file and it's also a bit more complex to implement.

The basic problem is that you're storing the decoded RGBA pixels array as a JPEG file - but they're not the same. Your code is basically correct: you just can't use this method to store it as a JPEG file. But if you happen to know that the image is, say, 800x600, you could create an 800x600 WriteableBitmap, and then set the Pixels property to the retrieved stream's byte array. Or if you don't know the dimensions when you're retrieving it, you could store the dimensions as the first two integers in the stream (before you write the pixels to the stream), and read out the dimensions when you're reading the file. You'd effectively be creating your own very simplistic .bmp format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top