Search code examples
androidxamarinxamarin.androidandroid-emulator

Download file in xamarin forms on android emulator


I'm trying to download a file from the server. After download, I don't get any errors so I suppose that file is downloaded but I can't find it in any folder. Is it because of an android emulator? I'm currently using Android 9.0 API 28.

public void DownloadFile(string url, string cookie)
{
  string pathToFolder-Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
  try
  {
    WebClient webClient=new WebClient();
    InitiatesSSLTrust();
    webClient.Headers.Add(HttpRequestHeader.Cookie, "JSESSIONID="+cookie);
    webclient.DownloadFileCompleted+=new AsyncCompletedEventHandler(Completed);
    string pathToNewFile=Path.Combine(pathToFolder, "plik.pdf");
    webClient.DownloadFileAsync(new Uri(url), pathToNewFile);
  }
  catch (Exception e)
  {
    if(OnFileDownloaded != null)
    {
      OnFileDownloaded.Invoke(this, new DownloadEventArgs(false));
    }
  }
}

Solution

  • string pathToFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

    the path will like

    "/data/user/0/packagename/files/plik.pdf"
    

    As you save it to Internal Storage,you couldn't see the files without root permission,if you want to view it,you could use adb tool (application signed by Android Debug)

    adb shell
    run-as packagename
    cd /data/data/packagename
    cd files
    ls
    

    then you could see the plik.pdf

    or you could save it to External storage,then you could find it in your device File Manager:

    //"/storage/emulated/0/Android/data/packagename/files/plik.pdf"
    string path = Android.App.Application.Context.GetExternalFilesDir(null).ToString();