public async Task Save(string filename, string contentType, MemoryStream stream) { var root = ""; //Get the root path in android device. if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; } else { root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); } var myDir = new Java.IO.File(root + "/Kişisel Takip"); var result = myDir.Mkdir(); //Directory.CreateDirectory(myDir.Path); var file = new Java.IO.File(myDir, filename); //if (file.Exists()) file.Delete(); var outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); }
public void put(string key, byte[] value) { var file = mCache.newFile(key); FileOutputStream output = null; try { output = new FileOutputStream(file); output.Write(value); } catch (System.Exception ex) { VPNLog.d("ACache", ex.ToString()); } finally { if (output != null) { try { output.Flush(); output.Dispose(); } catch (IOException ex) { ex.PrintStackTrace(); } } mCache.put(file); } }
protected override string RunInBackground(params string[] @params) { string strongPath = Android.OS.Environment.ExternalStorageDirectory.Path; string filePath = System.IO.Path.Combine(strongPath, "download.jpg"); int count; try { URL url = new URL(@params[0]); URLConnection connection = url.OpenConnection(); connection.Connect(); int LengthOfFile = connection.ContentLength; InputStream input = new BufferedInputStream(url.OpenStream(), LengthOfFile); OutputStream output = new FileOutputStream(filePath); byte[] data = new byte[1024]; long total = 0; while ((count = input.Read(data)) != -1) { total += count; PublishProgress("" + (int)((total / 100) / LengthOfFile)); output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); } catch (Exception e) { } return(null); }
private void ExportDatabaseToSdCard() { Log.D(this, "Exporting database"); try { var backup = new Java.IO.File(context.GetExternalFilesDir("").AbsolutePath, "ION_External.database"); var original = new Java.IO.File(database.path); Log.D(this, "Backup: " + backup.AbsolutePath); if (original.Exists()) { var fis = new FileInputStream(original); var fos = new FileOutputStream(backup); Log.D(this, "Transfered: " + fos.Channel.TransferFrom(fis.Channel, 0, fis.Channel.Size()) + " bytes"); fis.Close(); fos.Flush(); fos.Close(); Log.D(this, "Successfully exported the database to the sd card."); } } catch (Exception e) { Log.E(this, "Failed to export database to SD card", e); } }
private static string GetFileFromUrl(string fromUrl, string toFile) { try { URL url = new URL(fromUrl); URLConnection connection = url.OpenConnection(); connection.Connect(); //int fileLength = connection.GetContentLength(); // download the file InputStream input = new BufferedInputStream(url.OpenStream()); OutputStream output = new FileOutputStream(toFile); var data = new byte[1024]; long total = 0; int count; while ((count = input.Read(data)) != -1) { total += count; ////PublishProgress((int)(total * 100 / fileLength)); output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); } catch (Exception e) { Log.Error("YourApp", e.Message); } return(toFile); }
private static void copyAssets(Context context) { AssetManager assetManager = context.Assets; String appFileDirectory = context.FilesDir.Path; String executableFilePath = appFileDirectory + "/ffmpeg"; try { var fIn = assetManager.Open("ffmpeg"); Java.IO.File outFile = new Java.IO.File(executableFilePath); OutputStream fOut = null; fOut = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int read; while ((read = fIn.Read(buffer, 0, 1024)) > 0) { fOut.Write(buffer, 0, read); } fIn.Close(); fIn = null; fOut.Flush(); fOut.Close(); fOut = null; Java.IO.File execFile = new Java.IO.File(executableFilePath); execFile.SetExecutable(true); } catch (Exception e) { //Log.e(TAG, "Failed to copy asset file: " + filename, e); } }
/// <exception cref="System.Exception"/> private FilePath GetFileCommand(string clazz) { string classpath = Runtime.GetProperty("java.class.path"); FilePath fCommand = new FilePath(workSpace + FilePath.separator + "cache.sh"); fCommand.DeleteOnExit(); if (!fCommand.GetParentFile().Exists()) { fCommand.GetParentFile().Mkdirs(); } fCommand.CreateNewFile(); OutputStream os = new FileOutputStream(fCommand); os.Write(Sharpen.Runtime.GetBytesForString("#!/bin/sh \n")); if (clazz == null) { os.Write(Sharpen.Runtime.GetBytesForString(("ls "))); } else { os.Write(Sharpen.Runtime.GetBytesForString(("java -cp " + classpath + " " + clazz ))); } os.Flush(); os.Close(); FileUtil.Chmod(fCommand.GetAbsolutePath(), "700"); return(fCommand); }
/// <summary> /// Downloads the resource with the specified URI to a local file. /// </summary> public void DownloadFile(URL address, string fileName) { URLConnection connection = null; InputStream inputStream = null; OutputStream outputStream = new FileOutputStream(fileName); try { connection = OpenConnection(address); inputStream = connection.InputStream; var buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0) { outputStream.Write(buffer, 0, len); } outputStream.Flush(); } finally { if (inputStream != null) { inputStream.Close(); } var httpConnection = connection as HttpURLConnection; if (httpConnection != null) { httpConnection.Disconnect(); } outputStream.Close(); } }
private void SaveExcel(MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, "report.xlsx"); if (file.Exists()) file.Delete(); try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } }
protected override string RunInBackground(params string[] @params) { var storagePath = Android.OS.Environment.ExternalStorageDirectory.Path; var filePath = System.IO.Path.Combine(storagePath, $"{fileName}.jpg"); try { URL url = new URL(@params[0]); URLConnection connection = url.OpenConnection(); connection.Connect(); int lengthOfFile = connection.ContentLength; InputStream input = new BufferedInputStream(url.OpenStream(), lengthOfFile); OutputStream output = new FileOutputStream(filePath); byte[] data = new byte[1024]; long total = 0; int count = 0; while ((count = input.Read(data)) != -1) { total += count; PublishProgress($"{(int)(total / 100) / lengthOfFile}"); output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); return(string.Empty); } catch (Exception ex) { return(ex.Message); } }
private void CopyTestImageToSdCard(Java.IO.File testImageOnSdCard) { new Thread(new Runnable(() => { try { Stream is_ = Assets.Open(TEST_FILE_NAME); FileOutputStream fos = new FileOutputStream(testImageOnSdCard); byte[] buffer = new byte[8192]; int read; try { while ((read = is_.Read(buffer, 0, buffer.Length)) != -1) { fos.Write(buffer, 0, read); } } finally { fos.Flush(); fos.Close(); is_.Close(); } } catch (Java.IO.IOException e) { L.W("Can't copy test image onto SD card"); } })).Start(); }
private void copyDataBase() { Stream iStream = Assets.Open("database/cache.db"); string dbPath = "/data/data/hitec.Droid/files/cache.db"; //path "/data/data/camping.Droid/files/cache.db" var oStream = new FileOutputStream(dbPath); bool exists = System.IO.File.Exists(dbPath); long size = 0; Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(dbPath)); using (var fd = ContentResolver.OpenFileDescriptor(uri, "r")) size = fd.StatSize; if (size == 0) { byte[] buffer = new byte[2048]; int length = 2048; // length = Convert.ToInt16(length2); while (iStream.Read(buffer, 0, length) > 0) { oStream.Write(buffer, 0, length); } oStream.Flush(); oStream.Close(); iStream.Close(); } }
public void copy() { string path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "Notes3.db-wal"); // string path1 = "/data/user/0/com.companyname.Notes/files/Notes3.db"; File f = new File(path); // var fileex=f.Exists(); FileInputStream fis = null; FileOutputStream fos = null; fis = new FileInputStream(f); fos = new FileOutputStream("/mnt/sdcard/db_dump.db"); while (true) { int i = fis.Read(); if (i != -1) { fos.Write(i); } else { break; } } fos.Flush(); Toast.MakeText(Android.App.Application.Context, "DB dump OK", ToastLength.Short).Show(); fos.Close(); fis.Close(); }
public void Save(string filename, MemoryStream stream) { var root = Android.OS.Environment.DirectoryDownloads; var file = new Java.IO.File(root, filename); if (file.Exists()) file.Delete(); try { var outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { var f = e; } //if (file.Exists()) //{ // var path = Android.Net.Uri.FromFile(file); // var extension = // Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); // var mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); // var intent = new Intent(Intent.ActionOpenDocument); // intent.SetDataAndType(path, mimeType); // Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); //} }
private static void CopySQLiteDatabaseFromAssetsToData(Context context) { // Path to the just created empty db String outFileName = GetDBPath(context); if (System.IO.File.Exists(outFileName)) { return; } if (!System.IO.Directory.Exists(GetDBDirectory(context))) { System.IO.Directory.CreateDirectory(GetDBDirectory(context)); } //Open your local db as the input stream //Open the empty db as the output stream using (System.IO.Stream myInput = context.Assets.Open("shiplocations.sqlite")) using (FileOutputStream myOutput = new FileOutputStream(outFileName)) { //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.Read(buffer, 0, 1024)) > 0) { myOutput.Write(buffer, 0, length); } myOutput.Flush(); } //Close the streams /*myOutput.Flush(); * myOutput.Close(); * myInput.Close();*/ }
public async Task SaveAndView(string fileName, String contentType, MemoryStream stream) { string root = null; //Get the root path in android device. if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); } //Create directory and file Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); //Remove if the file exists if (file.Exists()) { file.Delete(); } //Write the stream into the file FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); //Invoke the created file for viewing if (file.Exists()) { Android.Net.Uri path = Android.Net.Uri.FromFile(file); var emailMessanger = CrossMessaging.Current.EmailMessenger; if (emailMessanger.CanSendEmail) { var email = new EmailMessageBuilder() .To("*****@*****.**") .Subject("Punches") .Body("Test Run") .WithAttachment(file) .Build(); emailMessanger.SendEmail(email); } //string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); //string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); //Intent intent = new Intent(Intent.ActionView); //intent.SetDataAndType(path, mimeType); //Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); } }
public void Save(string filename, string contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted) { ActivityCompat.RequestPermissions((Android.App.Activity)Forms.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1); } if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, filename); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { //Android.Net.Uri path = Android.Net.Uri.FromFile(file); //string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); //string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); //Intent intent = new Intent(Intent.ActionView); //intent.SetDataAndType(path, mimeType); //Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); Android.Net.Uri path = FileProvider.GetUriForFile(Forms.Context, Android.App.Application.Context.PackageName + ".provider", file); intent.SetDataAndType(path, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); } }
public string SaveAndViewAsync(string filename, MemoryStream stream) { try { string root = null; if (Environment1.IsExternalStorageEmulated) { root = Environment1.ExternalStorageDirectory.ToString(); } else { root = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } //Create directory and file Java.IO.File myDir = new Java.IO.File(root + "/DocScan"); myDir.Mkdir(); Java.IO.File myDir1 = new Java.IO.File(root + "/DocScan/Docs"); myDir1.Mkdir(); Java.IO.File file = new Java.IO.File(myDir1, filename); //Remove if the file exists if (file.Exists()) { file.Delete(); } //Write the stream into the file FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); if (file.Exists()) { uri1 path = supp.V4.Content.FileProvider.GetUriForFile(andApp.Application.Context, AppInfo.PackageName + ".fileprovider", file); string extension = andwebkit.MimeTypeMap.GetFileExtensionFromUrl(andNet.Uri.FromFile(file).ToString()); string mimeType = andwebkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent openFile = new Intent(); openFile.SetFlags(ActivityFlags.NewTask); openFile.SetFlags(ActivityFlags.GrantReadUriPermission); openFile.SetAction(andContent.Intent.ActionView); openFile.SetDataAndType(path, mimeType); Xamarin.Forms.Forms.Context.StartActivity(Intent.CreateChooser(openFile, "Choose App")); } return("Finish"); } catch (System.Exception ex) { string d = ex.ToString(); return("Error"); // } }
//*************************************************************************************************** //******************FUNCION QUE SE ENCARGA DEL PROCESO DE DESCARGA DE ARCHIVO*********************** //*************************************************************************************************** void DescargaArchivo(ProgressCircleView tem_pcv, string url_archivo) { //OBTENEMOS LA RUTA DONDE SE ENCUENTRA LA CARPETA PICTURES DE NUESTRO DISPOSITIVO Y LE CONCTENAMOS //EL NOMBRE DE UNA CARPETA NUEVA CARPETA, ES AQUI DONDE GUADAREMOS EL ARCHIVO A DESCARGAR string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath + "/DescargaImagen/"; Java.IO.File directory = new Java.IO.File(filePath); //VERIFICAMOS SI LA CARPETA EXISTE, SI NO LA CREAMOS if (directory.Exists() == false) { directory.Mkdir(); } //ESTABLECEMOS LA UBICACION DE NUESTRO ARCHIVO A DESCARGAR URL url = new URL(url_archivo); //CABRIMOS UNA CONEXION CON EL ARCHIVO URLConnection conexion = url.OpenConnection(); conexion.Connect(); //OBTENEMOS EL TAMAÑO DEL ARCHIVO A DESCARGAR int lenghtOfFile = conexion.ContentLength; //CREAMOS UN INPUTSTREAM PARA PODER EXTRAER EL ARCHIVO DE LA CONEXION InputStream input = new BufferedInputStream(url.OpenStream()); //ASIGNAMOS LA RUTA DONDE SE GUARDARA EL ARCHIVO, Y ASIGNAMOS EL NOMBRE CON EL QUE SE DESCARGAR EL ARCHIVO //PARA ESTE CASO CONSERVA EL MISMO NOMBRE string NewFile = directory.AbsolutePath + "/" + url_archivo.Substring(url_archivo.LastIndexOf("/") + 1); //CREAMOS UN OUTPUTSTREAM EN EL CUAL UTILIZAREMOS PARA CREAR EL ARCHIVO QUE ESTAMOS DESCARGANDO OutputStream output = new FileOutputStream(NewFile); byte[] data = new byte[lenghtOfFile]; long total = 0; int count; //COMENSAMOS A LEER LOS DATOS DE NUESTRO INPUTSTREAM while ((count = input.Read(data)) != -1) { total += count; //CON ESTA OPCION REPORTAMOS EL PROGRESO DE LA DESCARGA EN PORCENTAJE A NUESTRO CONTROL //QUE SE ENCUENTRA EN EL HILO PRINCIPAL RunOnUiThread(() => tem_pcv.setPorcentaje((int)((total * 100) / lenghtOfFile))); //ESCRIBIMOS LOS DATOS DELIDOS ES NUESTRO OUTPUTSTREAM output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); //INDICAMOS A NUESTRO PROGRESS QUE SE HA COMPLETADO LA DESCARGA AL 100% RunOnUiThread(() => tem_pcv.setPorcentaje(100)); }
public async Task SaveAndView(string fileName, MemoryStream stream) { string root = null; //Get the root path in android device. /* if (Android.OS.Environment.IsExternalStorageEmulated) * { * root = Android.OS.Environment.ExternalStorageDirectory.ToString(); * } * else*/ string target = @"C:\Users\Fanelle\Documents\TSR\Test"; root = target; /*if (!Directory.Exists(target)) * { * Directory.CreateDirectory(target); * }*/ //Environment.CurrentDirectory = target; // root = Directory.GetCurrentDirectory(); //Create directory and file //string path = @"D:\Python_Files\my_file.py"; /*Java.IO.File file = null; * using (file = File.Create(root)) ;*/ Java.IO.File myDir = new Java.IO.File(root); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); //Remove if the file exists //if (file.Exists()) file.Delete(); //Write the stream into the file FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); //Invoke the created file for viewing /*if (file.Exists()) * { * Android.Net.Uri path = Android.Net.Uri.FromFile(file); * string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); * string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); * Intent intent = new Intent(Intent.ActionView); * intent.SetDataAndType(path, mimeType); * Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); * }*/ }
public void WriteTxtToFile(string buffer, bool append) { Log.Info(Tag, "writeTxtToFile strFilePath =" + Path); RandomAccessFile raf = null; FileOutputStream outStream = null; try { File dir = new File(Path); if (!dir.Exists()) { dir.Mkdirs(); } File file = new File(Path + "/" + "Result.txt"); if (!file.Exists()) { file.CreateNewFile(); } if (append) { raf = new RandomAccessFile(file, "rw"); raf.Seek(file.Length()); raf.Write(Encoding.ASCII.GetBytes(buffer)); } else { outStream = new FileOutputStream(file); outStream.Write(Encoding.ASCII.GetBytes(buffer)); outStream.Flush(); } } catch (IOException e) { Log.Error(Tag, e.Message); } finally { try { if (raf != null) { raf.Close(); } if (outStream != null) { outStream.Close(); } } catch (IOException e) { Log.Error(Tag, e.Message); } } }
public void Save(string fileName, String contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } Java.IO.File myDir = new Java.IO.File(root + "/Lebenslauf"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { Android.Net.Uri path = Android.Net.Uri.FromFile(file); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(path, mimeType); //Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); try { Xamarin.Forms.Forms.Context.StartActivity(intent); } catch (Exception) { Toast.MakeText(Xamarin.Forms.Forms.Context, "Keine Anwendung verfügbar zum Anzeigen von WORD", ToastLength.Long).Show(); var urlStore = Device.OnPlatform("https://itunes.apple.com/ca/app/id683290832?mt=8", "https://play.google.com/store/apps/details?id=com.microsoft.office.word", ""); Device.OpenUri(new Uri(urlStore)); } } }
public string EnviarMensajeRecibirArchivo() { int bytesRead = 0; try { NetworkStream serverStream = clientSocket.GetStream(); byte[] outStream = Encoding.ASCII.GetBytes("Enviar archivo a dispositivo$"); serverStream.Write(outStream, 0, outStream.Length); serverStream.Flush(); // Recibimos el archivo y lo guardamos. MemoryStream memoryStream = new MemoryStream(); byte[] inStream = new byte[4096 * 8]; do { bytesRead = serverStream.Read(inStream, 0, inStream.Length); memoryStream.Write(inStream, 0, bytesRead); } while (bytesRead > 0); if (!Directory.Exists(Path.GetDirectoryName(FileName))) { Directory.CreateDirectory(Path.GetDirectoryName(FileName)); } Java.IO.File file = new Java.IO.File(FileName); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); outs.Write(memoryStream.ToArray()); outs.Flush(); outs.Close(); return("Archivo recibido."); } catch (Exception ex) { return("No se pudo recibir el archivo:\n" + ex.Message); } } catch (ArgumentOutOfRangeException) { throw new Exception("Algo anda mal con el tamaño del arreglo: " + bytesRead); } catch (Exception ex) { throw new Exception("Error desconocido:\n" + ex.Message); } } // EnviarMensajeRecibirArchivo()
/// <summary> /// Used to save a Exporting grid to Excel and PDF file in Android devices from Interface of ISAVE /// </summary> /// <param name="fileName">string type of filename parameter</param> /// <param name="contentType">string type of contentType parameter</param> /// <param name="stream">MemoryStream type of stream parameter</param> public void Save(string fileName, string contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); //// Forms.Context is obsolete, Hence used local context 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); Intent chooserIntent = Intent.CreateChooser(intent, "Open With"); chooserIntent.AddFlags(ActivityFlags.NewTask); Android.App.Application.Context.StartActivity(chooserIntent); } }
private async Task <string> WriteFileToCacheDirectory(string fileName, byte[] fileBytes) { File outputDir = this._context.CacheDir; File file = new File(outputDir, fileName); FileOutputStream fos = new FileOutputStream(file.AbsolutePath); await fos.WriteAsync(fileBytes); fos.Flush(); fos.Close(); return(file.AbsolutePath); }
private string DownloadFile(string sUrl, string filePath) { try { //get result from uri URL url = new Java.Net.URL(sUrl); URLConnection connection = url.OpenConnection(); connection.Connect(); // this will be useful so that you can show a tipical 0-100% // progress bar int lengthOfFile = connection.ContentLength; // download the file InputStream input = new BufferedInputStream(url.OpenStream(), 8192); // Output stream Log.WriteLine(LogPriority.Info, "DownloadFile FilePath ", filePath); OutputStream output = new FileOutputStream(filePath); byte[] data = new byte[1024]; long total = 0; int count; while ((count = input.Read(data)) != -1) { total += count; // publishing the progress.... // After this onProgressUpdate will be called //publishProgress("" + (int)((total * 100) / lengthOfFile)); if (total % 10 == 10) //log for every 10th increment { Log.WriteLine(LogPriority.Info, "DownloadFile Progress ", "" + (int)((total * 100) / lengthOfFile)); } // writing data to file output.Write(data, 0, count); } // flushing output output.Flush(); // closing streams output.Close(); input.Close(); } catch (Exception ex) { Log.WriteLine(LogPriority.Error, "DownloadFile Error", ex.Message); } return(filePath); }
private void SaveMessage(string message) { try { if (Context != null) { using (File dir = Context.GetDir("RaygunIO", FileCreationMode.Private)) { int number = 1; string[] files = dir.List(); while (true) { bool exists = FileExists(files, "RaygunErrorMessage" + number + ".txt"); if (!exists) { string nextFileName = "RaygunErrorMessage" + (number + 1) + ".txt"; exists = FileExists(files, nextFileName); if (exists) { DeleteFile(dir, nextFileName); } break; } number++; } if (number == 11) { string firstFileName = "RaygunErrorMessage1.txt"; if (FileExists(files, firstFileName)) { DeleteFile(dir, firstFileName); } } using (File file = new File(dir, "RaygunErrorMessage" + number + ".txt")) { using (FileOutputStream stream = new FileOutputStream(file)) { stream.Write(Encoding.ASCII.GetBytes(message)); stream.Flush(); stream.Close(); } } System.Diagnostics.Debug.WriteLine("Saved message: " + "RaygunErrorMessage" + number + ".txt"); System.Diagnostics.Debug.WriteLine("File Count: " + dir.List().Length); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(string.Format("Error saving message to isolated storage {0}", ex.Message)); } }
public void Save(string fileName, String contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } finally { if (contentType != "application/html") { stream.Dispose(); } } if (file.Exists() && contentType != "application/html") { Android.Net.Uri path = Android.Net.Uri.FromFile(file); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(path, mimeType); Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); } }
public void encrypt(string filename, string path) { // Here you read the cleartext. try { var extStore = new Java.IO.File("/storage/emulated/0/jukebox/Songs"); startTime = System.DateTime.Now.Millisecond; Android.Util.Log.Error("Encryption Started", extStore + "/" + filename); // This stream write the encrypted text. This stream will be wrapped by // another stream. createFile(filename, extStore); var webRequest = WebRequest.Create(path); using (var response = webRequest.GetResponse()) using (var content = response.GetResponseStream()) using (var reader = new StreamReader(content)) { var strContent = reader.ReadToEnd(); // System.IO.FileStream fs = System.IO.File.OpenWrite(path); FileOutputStream fos = new FileOutputStream(extStore + "/" + filename + ".aes", false); // Length is 16 byte Cipher cipher = Cipher.GetInstance("AES/CBC/PKCS5Padding"); byte[] raw = System.Text.Encoding.Default.GetBytes(sKey); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); IvParameterSpec iv = new IvParameterSpec(System.Text.Encoding.Default.GetBytes(ivParameter));// cipher.Init(Javax.Crypto.CipherMode.EncryptMode, skeySpec, iv); // Wrap the output stream CipherInputStream cis = new CipherInputStream(content, cipher); // Write bytes int b; byte[] d = new byte[1024 * 1024]; while ((b = cis.Read(d)) != -1) { fos.Write(d, 0, b); } // Flush and close streams. fos.Flush(); fos.Close(); cis.Close(); stopTime = System.DateTime.Now.Millisecond; Android.Util.Log.Error("Encryption Ended", extStore + "/5mbtest/" + filename + ".aes"); Android.Util.Log.Error("Time Elapsed", ((stopTime - startTime) / 1000.0) + ""); } } catch (Exception e) { Android.Util.Log.Error("lv", e.Message); } }
//Method to save document as a file in Android and view the saved document public async Task SaveAndView(string fileName, String contentType, MemoryStream stream) { string root = null; if (ContextCompat.CheckSelfPermission(Forms.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted) { ActivityCompat.RequestPermissions((Android.App.Activity)Forms.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1); } //Get the root path in android device. if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } //Create directory and file Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); //Remove if the file exists if (file.Exists()) { file.Delete(); } //Write the stream into the file FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); //Invoke the created file for viewing if (file.Exists()) { string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); Android.Net.Uri path = FileProvider.GetUriForFile(Forms.Context, Android.App.Application.Context.PackageName + ".provider", file); intent.SetDataAndType(path, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); } }
public void Print(string fileName, string contentType, MemoryStream stream) { string root; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } Java.IO.File myDir = new Java.IO.File($"{root}/Atas"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); stream.Position = 0; outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { Debug.WriteLine($"Print error: {e.ToString()}"); } finally { stream.Dispose(); } if (file.Exists()) { string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); var contentUri = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".fileprovider", file); intent.SetDataAndType(contentUri, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); intent.AddFlags(ActivityFlags.NewTask); intent.AddFlags(ActivityFlags.ClearTop); MainActivity.Instance.StartActivity(intent); } }
public void OnPictureTaken(byte[] data, Camera camera) { try { var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); File pictureFile = new File(path, "/" + Picture_Name); if (pictureFile.Exists()) { pictureFile.Delete(); } File NewPicture = new File(path, "/" + "face.JPG"); if (NewPicture.Exists()) { NewPicture.Delete(); } FileOutputStream file = null; FileOutputStream newfile = null; if (data != null) { try { file = new FileOutputStream(pictureFile); file.Write(data); file.Flush(); System.IO.MemoryStream imageStream = new System.IO.MemoryStream(data); var CurrentStatus = System.Convert.ToString(pictureFile.Path); MessagingCenter.Send(new MyMessage() { Myvalue = CurrentStatus }, "PictureTaken"); } catch (FileNotFoundException e) { } catch (IOException ie) { } finally { file?.Close(); } } File deleteFile = new File(pictureFile.Path); bool deleted = deleteFile.Delete(); } catch (Exception ex) { } }
public void Save(string fileName, String contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) file.Delete(); try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { Android.Net.Uri path = Android.Net.Uri.FromFile(file); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(path, mimeType); Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App")); } }
private void copyDataBase() { Stream iStream = Assets.Open("database/cache.db"); var oStream = new FileOutputStream ("/data/data/hitec.Droid/files/cache.db"); byte[] buffer = new byte[2048]; int length = 2048; // length = Convert.ToInt16(length2); while (iStream.Read(buffer, 0, length) > 0) { oStream.Write(buffer, 0, length); } oStream.Flush(); oStream.Close(); iStream.Close(); }
public static Java.IO.File bitmapToFile(Bitmap inImage) { //create a file to write bitmap data Java.IO.File f = new Java.IO.File(nn_context.CacheDir, "tempimgforfacebookshare"); f.CreateNewFile(); //Convert bitmap to byte array Bitmap bitmap = inImage; var bos = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 0, bos); byte[] bitmapdata = bos.ToArray (); //write the bytes in file FileOutputStream fos = new FileOutputStream(f); fos.Write(bitmapdata); fos.Flush(); fos.Close(); return f; }
protected override Java.Lang.Object DoInBackground (params Java.Lang.Object[] @params) { //REALIZAMOS EL PROCESO DE DESCARGA DEL ARCHIVO try{ string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ; Java.IO.File directory = new Java.IO.File (filePath); if(directory.Exists() ==false) { directory.Mkdir(); } //RECUPERAMOS LA DIRECCION DEL ARCHIVO QUE DESEAMOS DESCARGAR string url_link = @params [0].ToString (); URL url = new URL(url_link); URLConnection conexion = url.OpenConnection(); conexion.Connect (); int lenghtOfFile = conexion.ContentLength; InputStream input = new BufferedInputStream(url.OpenStream()); string NewImageFile = directory.AbsolutePath+ "/"+ url_link.Substring (url_link.LastIndexOf ("/") + 1); OutputStream output = new FileOutputStream(NewImageFile); byte[] data= new byte[lenghtOfFile]; int count; while ((count = input.Read(data)) != -1) { output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); return true; }catch { return false; } }
//*************************************************************************************************** //******************FUNCION QUE SE ENCARGA DEL PROCESO DE DESCARGA DE ARCHIVO*********************** //*************************************************************************************************** void DescargaArchivo(ProgressCircleView tem_pcv, string url_archivo) { //OBTENEMOS LA RUTA DONDE SE ENCUENTRA LA CARPETA PICTURES DE NUESTRO DISPOSITIVO Y LE CONCTENAMOS //EL NOMBRE DE UNA CARPETA NUEVA CARPETA, ES AQUI DONDE GUADAREMOS EL ARCHIVO A DESCARGAR string filePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures).AbsolutePath+"/DescargaImagen/" ; Java.IO.File directory = new Java.IO.File (filePath); //VERIFICAMOS SI LA CARPETA EXISTE, SI NO LA CREAMOS if(directory.Exists() ==false) { directory.Mkdir(); } //ESTABLECEMOS LA UBICACION DE NUESTRO ARCHIVO A DESCARGAR URL url = new URL(url_archivo); //CABRIMOS UNA CONEXION CON EL ARCHIVO URLConnection conexion = url.OpenConnection(); conexion.Connect (); //OBTENEMOS EL TAMAÑO DEL ARCHIVO A DESCARGAR int lenghtOfFile = conexion.ContentLength; //CREAMOS UN INPUTSTREAM PARA PODER EXTRAER EL ARCHIVO DE LA CONEXION InputStream input = new BufferedInputStream(url.OpenStream()); //ASIGNAMOS LA RUTA DONDE SE GUARDARA EL ARCHIVO, Y ASIGNAMOS EL NOMBRE CON EL QUE SE DESCARGAR EL ARCHIVO //PARA ESTE CASO CONSERVA EL MISMO NOMBRE string NewFile = directory.AbsolutePath+ "/"+ url_archivo.Substring (url_archivo.LastIndexOf ("/") + 1); //CREAMOS UN OUTPUTSTREAM EN EL CUAL UTILIZAREMOS PARA CREAR EL ARCHIVO QUE ESTAMOS DESCARGANDO OutputStream output = new FileOutputStream(NewFile); byte[] data= new byte[lenghtOfFile]; long total = 0; int count; //COMENSAMOS A LEER LOS DATOS DE NUESTRO INPUTSTREAM while ((count = input.Read(data)) != -1) { total += count; //CON ESTA OPCION REPORTAMOS EL PROGRESO DE LA DESCARGA EN PORCENTAJE A NUESTRO CONTROL //QUE SE ENCUENTRA EN EL HILO PRINCIPAL RunOnUiThread(() => tem_pcv.setPorcentaje ((int)((total*100)/lenghtOfFile))); //ESCRIBIMOS LOS DATOS DELIDOS ES NUESTRO OUTPUTSTREAM output.Write(data, 0, count); } output.Flush(); output.Close(); input.Close(); //INDICAMOS A NUESTRO PROGRESS QUE SE HA COMPLETADO LA DESCARGA AL 100% RunOnUiThread(() => tem_pcv.setPorcentaje (100)); }
private void copyDataBase() { Stream iStream = Assets.Open("database/cache.db"); string dbPath = "/data/data/camping.Droid/files/cache.db"; //path "/data/data/camping.Droid/files/cache.db" var oStream = new FileOutputStream (dbPath); bool exists = System.IO.File.Exists(dbPath); long size = 0; Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(dbPath)); using (var fd = ContentResolver.OpenFileDescriptor(uri, "r")) size = fd.StatSize; if ( size == 0 ) { byte[] buffer = new byte[2048]; int length = 2048; // length = Convert.ToInt16(length2); while (iStream.Read(buffer, 0, length) > 0) { oStream.Write(buffer, 0, length); } oStream.Flush(); oStream.Close(); iStream.Close(); } }
/// <summary> /// Downloads the resource with the specified URI to a local file. /// </summary> public void DownloadFile(URL address, string fileName) { URLConnection connection = null; InputStream inputStream = null; OutputStream outputStream = new FileOutputStream(fileName); try { connection = OpenConnection(address); inputStream = connection.InputStream; var buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0) { outputStream.Write(buffer, 0, len); } outputStream.Flush(); } finally { if (inputStream != null) inputStream.Close(); var httpConnection = connection as HttpURLConnection; if (httpConnection != null) httpConnection.Disconnect(); outputStream.Close(); } }