public string Save(MemoryStream stream) { string root = null; string fileName = "SavedDocument.pdf"; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); string filePath = file.Path; if (file.Exists()) { file.Delete(); } Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file); outs.Write(stream.ToArray()); var ab = file.Path; outs.Flush(); outs.Close(); return(filePath); }
public static async Task<Android.Net.Uri> DownloadDocument (Context ctx, Android.Net.Uri uriToDownload, string saveFilePath, IProgress<DownloadBytesProgress> progessReporter) { int receivedBytes = 0; int totalBytes = 0; using (var assetFileDescriptor = ctx.ContentResolver.OpenAssetFileDescriptor (uriToDownload, "r")) using (var fileOutputStream = new Java.IO.FileOutputStream (saveFilePath)) using (var inputStream = assetFileDescriptor.CreateInputStream ()) { var buffer = new byte [BufferSize]; totalBytes = (int)assetFileDescriptor.Length; for (;;) { var bytesRead = await inputStream.ReadAsync (buffer, 0, buffer.Length); if (bytesRead == 0) { await Task.Yield(); break; } await fileOutputStream.WriteAsync (buffer, 0, buffer.Length); receivedBytes += bytesRead; if (progessReporter != null) { var args = new DownloadBytesProgress (uriToDownload.ToString (), saveFilePath, receivedBytes, totalBytes); progessReporter.Report(args); } } inputStream.Close (); fileOutputStream.Close (); } var file = new Java.IO.File (saveFilePath); var docUri = Android.Net.Uri.FromFile (file); return docUri; }
private async Task <string> SaveFileToFolder(Android.Net.Uri uri, string fileName) { Android.Net.Uri docUri = Android.Provider.DocumentsContract.BuildDocumentUriUsingTree(uri, Android.Provider.DocumentsContract.GetTreeDocumentId(uri)); string fileFolder = SAFFileUtil.GetPath(this, docUri); Java.IO.File destFolder = new Java.IO.File(fileFolder); Java.IO.File file = new Java.IO.File(destFolder, fileName); Java.IO.File tempFile = new Java.IO.File(TempFilePath); destFolder.Mkdirs(); if (!file.Exists()) { file.CreateNewFile(); } Java.IO.FileInputStream fileInput = new Java.IO.FileInputStream(tempFile); Java.IO.FileOutputStream fileOutput = new Java.IO.FileOutputStream(file, false); while (true) { byte[] data = new byte[1024]; int read = await fileInput.ReadAsync(data, 0, data.Length); if (read <= 0) { break; } await fileOutput.WriteAsync(data, 0, read); } fileInput.Close(); fileOutput.Close(); return(file.AbsolutePath); }
private void PdfViewerControl_DocumentSaveInitiated(object sender, DocumentSaveInitiatedEventArgs args) { MemoryStream stream = args.SavedStream as MemoryStream; string root = null; string fileName = "sample.pdf"; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); } Java.IO.File directory = new Java.IO.File(root + "/Syncfusion"); directory.Mkdir(); Java.IO.File file = new Java.IO.File(directory, fileName); if (file.Exists()) { file.Delete(); } Java.IO.FileOutputStream outputStream = new Java.IO.FileOutputStream(file); outputStream.Write(stream.ToArray()); outputStream.Flush(); outputStream.Close(); AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainView.Context); alertDialog.SetTitle("Save"); alertDialog.SetMessage("The modified document is saved in the below location. " + "\n" + file.Path); alertDialog.SetPositiveButton("OK", (senderAlert, e) => { }); Dialog dialog = alertDialog.Create(); dialog.Show(); }
private void SavetoSd() { //var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path; //var filePath = System.IO.Path.Combine(sdCardPath, "iootext.txt"); //if (!System.IO.File.Exists(filePath)) //{ // using (System.IO.StreamWriter write = new System.IO.StreamWriter(filePath, true)) // { // write.Write(etSipServer.ToString()); // } //} var dirPath = this.FilesDir + "/KnowPool"; var exists = Directory.Exists(dirPath); var filepath = dirPath + "/cache_data.txt"; Console.WriteLine("Directory Path : " + filepath); if (!exists) { Directory.CreateDirectory(dirPath); if (!System.IO.File.Exists(filepath)) { var newfile = new Java.IO.File(dirPath, "cache_data.txt"); using (Java.IO.FileOutputStream outfile = new Java.IO.FileOutputStream(newfile)) { //string line = "The very first line!"; outfile.Write(System.Text.Encoding.ASCII.GetBytes(login_result_data)); outfile.Flush(); outfile.Close(); } } } else { if (!System.IO.File.Exists(filepath)) { var newfile = new Java.IO.File(dirPath, "cache_data.txt"); using (Java.IO.FileOutputStream outfile = new Java.IO.FileOutputStream(newfile)) { //string line = "The very first line!"; outfile.Write(System.Text.Encoding.ASCII.GetBytes(login_result_data)); outfile.Flush(); outfile.Close(); } } else { using (StreamWriter objStreamWriter = new StreamWriter(filepath, true)) { objStreamWriter.WriteLine(login_result_data); objStreamWriter.Flush(); objStreamWriter.Close(); } } } }
public void Copy(Context context, string fromFileName, Android.Net.Uri toUri, int bufferSize = 1024, CancellationToken?token = null) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(fromFileName)) { throw new ArgumentNullException(nameof(fromFileName)); } if (toUri == null) { throw new ArgumentNullException(nameof(toUri)); } if (!System.IO.File.Exists(fromFileName)) { throw new System.IO.FileNotFoundException(fromFileName); } if (token == null) { token = CancellationToken.None; } var buffer = new byte[bufferSize]; using (var readStream = System.IO.File.OpenRead(fromFileName)) { using (var openFileDescriptor = context.ContentResolver.OpenFileDescriptor(toUri, "w")) { using (var fileOutputStream = new Java.IO.FileOutputStream(openFileDescriptor.FileDescriptor)) { using (var bufferedStream = new System.IO.BufferedStream(readStream)) { int count; while ((count = bufferedStream.Read(buffer, 0, bufferSize)) > 0) { if (token.Value.IsCancellationRequested) { return; } fileOutputStream.Write(buffer, 0, count); } fileOutputStream.Close(); openFileDescriptor.Close(); } } } } }
public void Save(string filename, byte[] data) { var filepath = GetFilePath(filename); if (!System.IO.File.Exists(filepath)) { System.IO.File.Create(filepath); } Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(filepath); fos.Write(data); fos.Close(); }
public static void SaveFileToStorage(Java.IO.File f) { if (f == null) { return; } try { Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(f); fos.Close(); } catch (FileNotFoundException e) { } catch (IOException e) { } }
public override void OnPageFinished(global::Android.Webkit.WebView myWebview, string url) { PdfDocument document = new PdfDocument(); PdfDocument.Page page = document.StartPage(new PdfDocument.PageInfo.Builder(width, height, 1).Create()); myWebview.Draw(page.Canvas); document.FinishPage(page); Stream filestream = new MemoryStream(); Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(fileNameWithPath, false); document.WriteTo(filestream); fos.Write(((MemoryStream)filestream).ToArray(), 0, (int)filestream.Length); fos.Close(); }
public void OnPictureTaken(byte[] data, Camera camera) { Task.Run(() => { var directoryPictures = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); var directory = new Java.IO.File(directoryPictures, Constants.Steepshot); if (!directory.Exists()) { directory.Mkdirs(); } var photoUri = $"{directory}/{Guid.NewGuid()}.jpeg"; var stream = new Java.IO.FileOutputStream(photoUri); stream.Write(data); stream.Close(); var exifInterface = new ExifInterface(photoUri); var orientation = exifInterface.GetAttributeInt(ExifInterface.TagOrientation, 0); if (orientation != 1 && orientation != 0) { var bitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length); bitmap = BitmapUtils.RotateImage(bitmap, _rotationOnShutter); var rotationStream = new System.IO.FileStream(photoUri, System.IO.FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, rotationStream); } var i = new Intent(Context, typeof(PostDescriptionActivity)); i.PutExtra(PostDescriptionActivity.PhotoExtraPath, photoUri); i.PutExtra(PostDescriptionActivity.IsNeedCompressExtraPath, false); Activity.RunOnUiThread(() => { StartActivity(i); Activity.Finish(); if (_progressBar != null) { _progressBar.Visibility = ViewStates.Gone; _shotButton.Visibility = ViewStates.Visible; _flashButton.Enabled = true; _galleryButton.Enabled = true; _revertButton.Enabled = true; _closeButton.Enabled = true; } }); }); }
public void SaveFile(byte[] data, string url) { try { Java.IO.File f = new Java.IO.File(Android.App.Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures), url); f.CreateNewFile(); Java.IO.FileOutputStream fs = new Java.IO.FileOutputStream(f); fs.Write(data); fs.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
private void CreateFileJava(string fileName, byte[] data) { var path = Environment.ExternalStorageDirectory + Java.IO.File.Separator + fileName; var file = new Java.IO.File(path); file.CreateNewFile(); if (file.Exists()) { Java.IO.OutputStream fo = new Java.IO.FileOutputStream(file); fo.Write(data); fo.Close(); Toast.MakeText(this, $"File created at {path}", ToastLength.Short).Show(); } else { Toast.MakeText(this, "Failed to create file", ToastLength.Short).Show(); } }
public void OnPictureTaken(byte[] data, Camera camera) { Task.Run(() => { var directory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim); var photoUri = $"{directory}/{Guid.NewGuid()}.jpeg"; var stream = new Java.IO.FileOutputStream(photoUri); stream.Write(data); stream.Close(); var exifInterface = new ExifInterface(photoUri); var orientation = exifInterface.GetAttributeInt(ExifInterface.TagOrientation, 0); if (orientation != 1 && orientation != 0) { var bitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length); bitmap = BitmapUtils.RotateImage(bitmap, _rotationOnShutter); var rotationStream = new System.IO.FileStream(photoUri, System.IO.FileMode.Create); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, rotationStream); } var model = new GalleryMediaModel { Path = photoUri }; Activity.RunOnUiThread(() => { ((BaseActivity)Activity).OpenNewContentFragment(new PostEditFragment(model)); if (_progressBar != null) { _progressBar.Visibility = ViewStates.Gone; _shotButton.Visibility = ViewStates.Visible; _flashButton.Enabled = true; _galleryButton.Enabled = true; _revertButton.Enabled = true; _closeButton.Enabled = true; } }); }); }
public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName) { try { _location = destinationDirectoryName; if (!_location.EndsWith("/")) { _location += "/"; } var fileInputStream = new FileStream(sourceArchiveFileName, FileMode.Open); var zipInputStream = new ZipInputStream(fileInputStream); ZipEntry zipEntry = null; while ((zipEntry = zipInputStream.NextEntry) != null) { xLog.Debug("UnZipping : " + zipEntry.Name); if (zipEntry.IsDirectory) { DirChecker(zipEntry.Name); } else { var fileOutputStream = new Java.IO.FileOutputStream(_location + zipEntry.Name); for (int i = zipInputStream.Read(); i != -1; i = zipInputStream.Read()) { fileOutputStream.Write(i); } zipInputStream.CloseEntry(); fileOutputStream.Close(); } } zipInputStream.Close(); } catch (Exception ex) { xLog.Error(ex); } }
public async Task SaveJpg(byte[] img) { string path = Path.Combine( Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).Path, "TikiTreiler"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string jpgFilename = Path.Combine(path, DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss-ffff") + ".jpg"); // Doing it the C# way threw a security exception :S. Java.IO.FileOutputStream outStream = new Java.IO.FileOutputStream(jpgFilename); try { outStream.Write(img); } catch (Java.Lang.Exception) { throw new Java.Lang.IllegalArgumentException(); } finally { outStream.Close(); } }
public void CacheData(Context context, string key, byte[] data, bool append) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } if (data == null || data.Length == 0) { return; } using (var cacheDir = GetCacheDir(context)) { var size = cacheDir.TotalSpace - cacheDir.FreeSpace; var dataSize = data.Length; var newSize = dataSize + size; if (newSize > MaxSizeByte) { Clear(cacheDir, newSize - MaxSizeByte); } if (dataSize > MaxSizeByte) { return; } using (var file = new Java.IO.File(cacheDir, key)) { using (var stream = new Java.IO.FileOutputStream(file, append)) { stream.Write(data); stream.Flush(); stream.Close(); } } } }
public static void SaveVideoToExternalStorage(string path) { Java.IO.File root = Android.OS.Environment.ExternalStorageDirectory; Java.IO.File appDir = new Java.IO.File(root, "Ta7meelVideos"); if (!appDir.Exists()) { if (!appDir.Mkdir()) { return; } } Java.IO.File videoDownloadedFile = new Java.IO.File(path); Java.IO.File file = new Java.IO.File(appDir, videoDownloadedFile.Name); if (!file.Exists()) { try { Java.IO.FileInputStream videoToCopy = new Java.IO.FileInputStream(videoDownloadedFile); Java.IO.FileOutputStream copyOfVideo = new Java.IO.FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = videoToCopy.Read(buf)) > 0) { copyOfVideo.Write(buf, 0, len); } copyOfVideo.Flush(); copyOfVideo.Close(); videoToCopy.Close(); String[] Pathes = new String[] { file.Path }; MediaScannerConnection.ScanFile(Forms.Context, Pathes, null, null); } catch (Exception e) { e.GetType(); } } }
/// <summary> /// 外部intentで選択したファイルをアプリ専用ディレクトリ領域に一時フィアルとして保存する。 /// </summary> private Java.IO.File SaveBookShelfTempFile(Intent data) { //出力ファイルを用意する Java.IO.File cacheFile = new Java.IO.File(this.ExternalCacheDir, "bookshelf_cache.txt"); try { //入力ファイル using (System.IO.Stream fis = this.ContentResolver.OpenInputStream(data.Data)) { //出力ファイル Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(cacheFile); byte[] buf = new byte[32768]; // 一時バッファ int len = 0; while (true) { len = fis.Read(buf, 0, buf.Length); if (len > 0) { fos.Write(buf, 0, len); } else { break; } } //ファイルに書き込む fos.Flush(); fos.Close(); fis.Close(); } return(cacheFile); } catch (Exception ex) { return(null); } }
public static async Task <Android.Net.Uri> DownloadDocument(Context ctx, Android.Net.Uri uriToDownload, string saveFilePath, IProgress <DownloadBytesProgress> progessReporter) { int receivedBytes = 0; int totalBytes = 0; using (var assetFileDescriptor = ctx.ContentResolver.OpenAssetFileDescriptor(uriToDownload, "r")) using (var fileOutputStream = new Java.IO.FileOutputStream(saveFilePath)) using (var inputStream = assetFileDescriptor.CreateInputStream()) { var buffer = new byte [BufferSize]; totalBytes = (int)assetFileDescriptor.Length; for (;;) { var bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead == 0) { await Task.Yield(); break; } await fileOutputStream.WriteAsync(buffer, 0, buffer.Length); receivedBytes += bytesRead; if (progessReporter != null) { var args = new DownloadBytesProgress(uriToDownload.ToString(), saveFilePath, receivedBytes, totalBytes); progessReporter.Report(args); } } inputStream.Close(); fileOutputStream.Close(); } var file = new Java.IO.File(saveFilePath); var docUri = Android.Net.Uri.FromFile(file); return(docUri); }
public static void Cache(Context context, byte[] data, String name) { Java.IO.File cacheDir = context.CacheDir; long size = GetDirSize(cacheDir); long newSize = data.Length + size; if (newSize > MAX_CACHE_SIZE) { CleanDir(cacheDir, newSize - MAX_CACHE_SIZE); } Java.IO.File file = new Java.IO.File(cacheDir, name); Java.IO.FileOutputStream os = new Java.IO.FileOutputStream(file); try { os.Write(data); } finally { os.Flush(); os.Close(); } }
public async Task <string> Save(byte[] data, string thefileName) { string root = null; string fileName = thefileName; root = await GetPath(); root = Path.Combine(root, Android.OS.Environment.DirectoryDownloads); Java.IO.File file = new Java.IO.File(root, fileName); string filePath = file.Path; if (file.Exists()) { file.Delete(); } Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file); outs.Write(data); var ab = file.Path; outs.Flush(); outs.Close(); return(filePath); }
public bool IsReadOnlyBecauseKitkatRestrictions(IOConnectionInfo ioc) { if (IsLocalFileFlaggedReadOnly(ioc)) return false; //it's not read-only because of the restrictions introduced in kitkat try { //test if we can open //http://www.doubleencore.com/2014/03/android-external-storage/#comment-1294469517 using (var writer = new Java.IO.FileOutputStream(ioc.Path, true)) { writer.Close(); return false; //we can write } } catch (Java.IO.IOException) { //seems like we can't write to that location even though it's not read-only return true; } }
private void playMp3(byte[] mp3SoundByteArray) { try { // create temp file that will hold byte array Java.IO.File tempMp3 = Java.IO.File.CreateTempFile("kurchina", "mp3", CacheDir); tempMp3.DeleteOnExit(); Java.IO.FileOutputStream fos = new Java.IO.FileOutputStream(tempMp3); fos.Write(mp3SoundByteArray); fos.Close(); Java.IO.FileInputStream fis = new Java.IO.FileInputStream(tempMp3); player.SetDataSource(fis.FD); player.Prepare(); player.Start(); } catch (Java.IO.IOException ex) { String s = ex.ToString (); ex.PrintStackTrace (); } }
/// <summary> /// Writes data to given filepath whilst recording audio. /// </summary> private void WriteAudioDataToFile() { // Get audio sample length short[] sData = new short[bufferSizeBytes / 2]; Java.IO.FileOutputStream os = null; try { os = new Java.IO.FileOutputStream(filePath); } catch (FileNotFoundException e) { Console.WriteLine(e); } while (isRecording) { // Gets the voice output from microphone to byte format audioRecorder.Read(sData, 0, bufferSizeBytes/2); try { // Writes the data to file from buffer byte[] bData = short2byte(sData); os.Write(bData, 0, bufferSizeBytes); } catch (IOException e) { Console.WriteLine(e); } } try { os.Close(); } catch (IOException e) { Console.WriteLine(e); } }
private void Reproducir(Cancion cancion) { Action action = new Action(DesactivarControles); Handler.Post(action); byte[] archivo = null; bool huboExcepcion = false; APIGatewayService api = new APIGatewayService(); if (!UtileriasDeArchivos.CancionYaDescargada(cancion.IdArchivo)) { try { archivo = api.DescargarArchivoPorId(cancion.IdArchivo); cancion.CargarMetadatosDeLaCancion(Usuario.Id); } catch (System.Exception) { Toast.MakeText(View.Context, "Error al realizar la descarga, intente de nuevo mas tarde", ToastLength.Long).Show(); huboExcepcion = true; } } else { try { archivo = UtileriasDeArchivos.LeerArchivoPorId(cancion.IdArchivo); } catch (ArgumentException) { huboExcepcion = true; } } if (!huboExcepcion && archivo != null && archivo.Length > 0) { if (Canciones[IndiceActual].Metadatos == null) { bool resultado = false; try { resultado = api.CrearNuevoMetadato(Usuario.Id, Canciones[IndiceActual].Id); } catch (Exception) { Toast.MakeText(View.Context, "No se pudo registrar el MeGusta", ToastLength.Long).Show(); } if (!resultado) { Toast.MakeText(View.Context, "No se pudo registrar el MeGusta", ToastLength.Long).Show(); } else { Canciones[IndiceActual].CargarMetadatosDeLaCancion(Usuario.Id); } } var buttonLike = View.FindViewById <ImageButton>(Resource.Id.ibtnLike); if (cancion.Metadatos.MeGusta) { buttonLike.SetImageDrawable(View.Context.GetDrawable(Resource.Drawable.ic_ss_like)); } else { buttonLike.SetImageDrawable(View.Context.GetDrawable(Resource.Drawable.ic_ss_dislike)); } var buttonReproducir = View.FindViewById <ImageButton>(Resource.Id.ibtnReproducir); buttonReproducir.SetImageDrawable(View.Context.GetDrawable(Resource.Drawable.ic_ss_pausa)); var txtCancion = View.FindViewById <TextView>(Resource.Id.txtNombreCancion); txtCancion.Text = cancion.Nombre; var txtArtista = View.FindViewById <TextView>(Resource.Id.txtNombreArtista); if (cancion.Artistas.FirstOrDefault() != null) { txtArtista.Text = cancion.Artistas.FirstOrDefault().Nombre; } var txtTiempoTotal = View.FindViewById <TextView>(Resource.Id.txtDuracionTotal); TimeSpan tiempoActual = TimeSpan.FromMilliseconds(Reproductor.Duration); txtTiempoTotal.Text = System.String.Format("{0}:{1:D2}", tiempoActual.Minutes, tiempoActual.Seconds); try { Reproductor.Reset(); Java.IO.File archivoTemporal = Java.IO.File.CreateTempFile(cancion.Id, "mp3", Context.CacheDir); archivoTemporal.DeleteOnExit(); Java.IO.FileOutputStream outputStream = new Java.IO.FileOutputStream(archivoTemporal); outputStream.Write(archivo); outputStream.Close(); Java.IO.FileInputStream fis = new Java.IO.FileInputStream(archivoTemporal); Reproductor.SetDataSource(fis.FD); Reproductor.Prepare(); Reproductor.Start(); CancionCorriendo = true; } catch (System.Exception e) { Toast.MakeText(View.Context, e.Message, ToastLength.Long).Show(); } AgregarCancionAHistorial(cancion.Id); } action = new Action(ActivarControles); Handler.Post(action); ActualizadorCorriendo = true; }
public async Task SaveAndView(string fileName, string contentType, MemoryStream stream, PDFOpenContext context) { string exception = string.Empty; string root = null; if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted) { ActivityCompat.RequestPermissions((Activity)Android.App.Application.Context, new string[] { Manifest.Permission.WriteExternalStorage }, 1); } //if (Android.OS.Environment.IsExternalStorageEmulated) //{ // root = Android.OS.Environment.ExternalStorageDirectory.ToString(); //} //else // root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(Path.Combine(root, "PDFFiles")); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } //file.CreateNewFile(); try { Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); Android.Net.Uri path = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file); intent.SetDataAndType(path, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); switch (context) { default: case PDFOpenContext.InApp: Android.App.Application.Context.StartActivity(intent); break; case PDFOpenContext.ChooseApp: Android.App.Application.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); break; } } }