Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7566409
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T14:24:18+00:00 2026-05-30T14:24:18+00:00

I am developing a music player in wp7 using silverlight.My end users don’t have

  • 0

I am developing a music player in wp7 using silverlight.My end users don’t have good internet connection when they are roaming. I want to give them an option to download music in their phone.
For that i have written a download manager which they can use to download music when they have wifi connection.
I ussue i am facing is that,My music is stored on my server and i am downloading the music on the phone using WebCLient class.
if size of file goes beyond 68 MB , my application gets OutOfMemory exception.
here is the code:

public void DownloadKirtan(KirtanViewModel kirtanVm,bool QueueItem=true)
{

        {
            if (kirtanVm.LocationPath != null)
            {
                WebClient webClient = new WebClient();
                //webClient.AllowWriteStreamBuffering = false;
               // webClient.AllowReadStreamBuffering = false;
                if (QueueItem == false)
                {
                    //App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload[kirtanVm] = webClient;
                   // App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload.Add(kirtanVm//
                    webClient = App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload[kirtanVm];
                    kirtanVm.IsDownloadedForOfflineViewing = "Started";
                    webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
                    webClient.OpenReadAsync(kirtanVm.LocationPath, kirtanVm);
                }
                else if (!App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload.ContainsKey(kirtanVm))
                {
                    App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload.Add(kirtanVm, webClient);
                    kirtanVm.IsDownloadedForOfflineViewing = "Started";
                    webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
                    webClient.OpenReadAsync(kirtanVm.LocationPath, kirtanVm);


                }
                // webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);

            }
        }
    }

void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{

        KirtanViewModel kirtanVm = e.UserState as KirtanViewModel;
        try
        {
            if (e.Cancelled == false)
            {
                if (e.Result != null)
                {

                    ((WebClient)sender).OpenReadCompleted -= webClient_OpenReadCompleted;

                    #region Isolated Storage Copy Code


                    IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();



                    bool checkQuotaIncrease =  IncreaseIsolatedStorageSpace(e.Result.Length);


                    if (checkQuotaIncrease)
                    {

                        string VideoFile = "";
                        VideoFile = GetUrlOfOfflineContent(kirtanVm);

                        using (IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile))
                        {
                            long VideoFileLength = (long)e.Result.Length;


                            byte[] byteImage = new byte[VideoFileLength];

                            e.Result.Read(byteImage, 0, byteImage.Length);

                                isolatedStorageFileStream.Write(byteImage, 0, byteImage.Length);


                                        kirtanVm.IsDownloadedForOfflineViewing = "True";
                                        kirtanVm.DownloadSize = "Size=" + (VideoFileLength / 1000000).ToString() + " MB";
                                        kirtanVm.DownloadProgress = "100%";
                                        Settings.OfflineKirtanContents.Value.Add(kirtanVm);
                                        AddRemoveKirtanInOfflineModels(kirtanVm, true);





                        }

                    #endregion
                    }
                    else
                    {
                        kirtanVm.IsDownloadedForOfflineViewing = "False";
                        App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload.Remove(kirtanVm);
                        MessageBox.Show("There is not enough space in your phone to store this media. You need " + e.Result.Length + " bytes of storage.Please free some offline contents you have downloaded by going to Offline content managemnt screen in Settings Section and try again or increase the storage on your phone.");
                    }



                    // mediaFile.SetSource(isolatedStorageFileStream);

                    // mediaFile.Play();

                    // progressMedia.Visibility = Visibility.Collapsed;





                  }
            }

        }

        catch (Exception ex)
        {
            kirtanVm.IsDownloadedForOfflineViewing = "Failed";

            //App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload.Remove(kirtanVm);
           MessageBox.Show(ex.ToString());

        }

    }

The problem i am having is When i get e.result which is a stream object. To write to isolatedStoreFileStream, i have to read it again to byte array and then save it to isolatedstoragefile. This is inefficient, it consumes double memory. Memory of 60 MB (for 60MB file) by WebClient e.result stream object and then 60 MB to convert to array. So memory consumtion is 128 MB . Is there is better way to download big files and store it to IsolatedStorage>

UPDATE : I am now using following code using the chunck size , instead of reading all in memory but i still get out of memory error on large files 100 MB

void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{

        KirtanViewModel kirtanVm = e.UserState as KirtanViewModel;
        try
        {
            if (e.Cancelled == false)
            {
                if (e.Result != null)
                {

                    ((WebClient)sender).OpenReadCompleted -= webClient_OpenReadCompleted;

                    #region Isolated Storage Copy Code
                    bool checkQuotaIncrease =  IncreaseIsolatedStorageSpace(e.Result.Length);
                    if (checkQuotaIncrease)
                    {

                        string VideoFile = "";
                        VideoFile = GetUrlOfOfflineContent(kirtanVm);
                        ThreadPool.QueueUserWorkItem( k =>{
                        using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile))
                            {
                                long VideoFileLength = (long)e.Result.Length;


                                using (BinaryWriter writer = new BinaryWriter(isolatedStorageFileStream))
                                {
                                    Stream resourceStream = e.Result;//streamResourceInfo.Stream;
                                    long length = resourceStream.Length;
                                    byte[] buffer = new byte[32];
                                    int readCount = 0;
                                    using (BinaryReader reader = new BinaryReader(resourceStream))
                                    {                    // read file in chunks in order to reduce memory consumption and increase performance                    
                                        while (readCount < length)
                                        {
                                            int actual = reader.Read(buffer, 0, buffer.Length);
                                            readCount += actual;
                                            writer.Write(buffer, 0, actual);
                                        }
                                    }
                                }
                                 kirtanVm.IsDownloadedForOfflineViewing = "True";
                                kirtanVm.DownloadSize = "Size=" + (VideoFileLength / 1000000).ToString() + " MB";
                                kirtanVm.DownloadProgress = "100%";
                                Settings.OfflineKirtanContents.Value.Add(kirtanVm);
                                AddRemoveKirtanInOfflineModels(kirtanVm, true);
                            }
                        }
                       });

                                //byte[] byteImage = new byte[VideoFileLength];

                                //e.Result.Read(byteImage, 0, byteImage.Length);
                                // e.re
                                //ThreadPool.QueueUserWorkItem( k =>{
                                //     isolatedStorageFileStream.Write(byteImage, 0, byteImage.Length);
                                //isolatedStorageFileStream.Close();
                                //Application.Current.RootVisual.Dispatcher.BeginInvoke( ()=>
                                //    {
                                //        kirtanVm.IsDownloadedForOfflineViewing = "True";
                                //        kirtanVm.DownloadSize = "Size=" + (VideoFileLength / 1000000).ToString() + " MB";
                                //        kirtanVm.DownloadProgress = "100%";
                                //        Settings.OfflineKirtanContents.Value.Add(kirtanVm);
                                //        AddRemoveKirtanInOfflineModels(kirtanVm, true);
                                //    });

                                //});
                                //StreamWriter writer=new StreamWriter(isolatedStorageFileStream);
                                // writer.Write(e.Result);
                                // writer.Close();
                                // isolatedStorageFileStream.Write(
                                // e.Result.Write(

                              //  isolatedStorageFileStream.Write(byteImage, 0, byteImage.Length);
                                // isolatedStorageFileStream.Close();




                            }


                    #endregion

                    else
                    {
                        kirtanVm.IsDownloadedForOfflineViewing = "False";
                        App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload.Remove(kirtanVm);
                        MessageBox.Show("There is not enough space in your phone to store this media. You need " + e.Result.Length + " bytes of storage.Please free some offline contents you have downloaded by going to Offline content managemnt screen in Settings Section and try again or increase the storage on your phone.");
                    }

                }
            }
            else
            {
                lock (App.ViewModel.LockForCancelForCurrentOfflineDownload)
                {
                    if (App.ViewModel.cancelInitiatedByUserForCurrentOfflineDownload)
                    {
                        kirtanVm.IsDownloadedForOfflineViewing = "False";
                       // kirtanVm.IsOfflineDownloadCancelled = false;
                        App.ViewModel.cancelInitiatedByUserForCurrentOfflineDownload = false;
                    }
                    else
                    {
                        if (kirtanVm.IsDownloadedForOfflineViewing == "Started")// don't queue things again
                        {
                            kirtanVm.IsDownloadedForOfflineViewing = "Failed";
                            // bool ItemExist = App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload.Any(k => k.Key.Kirtan.KirtanId == kirtanVm.Kirtan.KirtanId);

                            DownloadKirtan(kirtanVm, false);
                        }
                    }
                }
            }



        }

        catch (Exception ex)
        {
            kirtanVm.IsDownloadedForOfflineViewing = "Failed";

            //App.ViewModel.ActiveInstancesOfWebClientForKirtanDownload.Remove(kirtanVm);
           MessageBox.Show(ex.ToString());

        }

    }

Thanks
Verinder

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T14:24:20+00:00Added an answer on May 30, 2026 at 2:24 pm

    Finally i found the solution

    turn on webClient.AllowReadStreamBuffering = false; in the above code which i shared and then in
    void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {} method.. Remove all refrences to e.Result.Length. When using no buffering solution you cannot know the stream size in advance

    long length = resourceStream.Length;                                     
    byte[] buffer = new byte[1024];                                     
    int readCount = 0;                                     
    using (BinaryReader reader = new BinaryReader(resourceStream))                                     {                    // read file in chunks in order to reduce memory consumption and increase performance                                                             
    while (true)                                         
    {       
    int actual = reader.Read(buffer, 0, 1024);   
     if(actual==0)
    {
     break;
    }
    else
       {                                      
     readCount += actual;                                             
    writer.Write(buffer, 0, actual);  
    }                                       
    }                                     
    }
    

    Keep on reading the stream with 1024 bytes at a time unless you are done reading. This way WebClient will not buffer whole file in memory and max mem usage on your phone will be 1KB at a time. You can download Gigs of data like this. INcrease the buffer size to 1MB or 3 MB , if you want to read faster.
    Make sure you run this code in ThreadPool instead of user thread

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm developing an app using Heroku but they don't have the plpgsql language loaded
I am using Qt SDK 4.6 for developing a simple music player on windows
I am developing an application for music. I have an Activity where I have
I have an app I'm developing which relies heavily on users being able to
I'm developing an iPhone game and currently using AVAudioPlayer for playing background music and
I'm developing a music player based on jQuery, which has a long list of
I'm developing an music/video player app and just need to konw how to disable
I'm developing an OS X application to organize things (as iTunes is to music
Developing a project of mine I realize I have a need for some level
I am developing a music mixing app in iphone. It'll mix the music and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.