J. Joe
J. Joe

Reputation: 381

Can't save file to the device on xamarin android

async void ImgDownload_Click (object sender, EventArgs e)
        {
            var webClient=new WebClient();
        var url=new Uri(stream_url_soundcloud);
        byte[] bytes=null;


        webClient.DownloadProgressChanged+= WebClient_DownloadProgressChanged;
        dialog = new ProgressDialog (this);
        dialog.SetProgressStyle (ProgressDialogStyle.Horizontal);
        dialog.SetTitle("Downloading...");
        dialog.SetCancelable (false);
        //dialog.SetButton("Cancel",);
        dialog.SetCanceledOnTouchOutside (false);
        dialog.Show ();

        try
        {
            bytes= await webClient.DownloadDataTaskAsync(url);
        }
        catch(TaskCanceledException)
        {
            Toast.MakeText(this,"Task Canceled!",ToastLength.Long);
            return;
        }
        catch(Exception a)
        {
            Toast.MakeText(this,a.InnerException.Message,ToastLength.Long);
            dialog.Progress=0;
            return;
        }

        Java.IO.File documentsPath= new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMusic),"MusicDownloaded");
        string localFilename = documentsPath + mListData[mPosition].track.title+".mp3";
        //string localPath=System.IO.Path.Combine(documentsPath,localFilename);
        Java.IO.File localPath=new Java.IO.File(documentsPath,localFilename);

        dialog.SetTitle("Download Complete");

        //Save the Mp3 using writeAsync
        //FileStream fs=new FileStream(localPath,FileMode.OpenOrCreate);
        OutputStream fs=new FileOutputStream(localPath);
        await fs.WriteAsync (bytes, 0, bytes.Length);

        fs.Close ();


        dialog.Progress = 0;
        }

        void WebClient_DownloadProgressChanged (object sender, DownloadProgressChangedEventArgs e)
        {
            dialog.Progress = e.ProgressPercentage;
            if (e.ProgressPercentage == 100) {
                //dialog.Hide ();
            }
        }

enter image description here

Download an image successful but I find it on my device but I don't see it.

In Document get emty and Download History also get emty.

I don't understand. I want to save it in photos on device. I use Samsung Galaxy.

Upvotes: 0

Views: 492

Answers (1)

Danil Kurkin
Danil Kurkin

Reputation: 283

Have a look at this post.

I believe that you can write and read from external storage public directory only.

Good luck!

Upvotes: 1

Related Questions