/// <summary> /// Read a file with given path and return a byte-array with it's entire contents. /// </summary> public static byte[] ReadAllBytes(string path) { if (path == null) { throw new ArgumentNullException("path"); } var file = new JFile(path); if (!file.Exists() || !file.IsFile) { throw new FileNotFoundException(path); } if (!file.CanRead) { throw new UnauthorizedAccessException(path); } var stream = new FileInputStream(file); try { var array = new byte[file.Length()]; stream.Read(array, 0, array.Length); return(array); } finally { stream.Close(); } }
public static byte[] readFile(String filePath) { byte[] contents; Java.IO.File file = new Java.IO.File(filePath); int size = (int)file.Length(); contents = new byte[size]; try { FileStream inputStream = new FileStream(filePath, FileMode.OpenOrCreate); Java.IO.BufferedOutputStream bos = new Java.IO.BufferedOutputStream(inputStream); BufferedInputStream buf = new BufferedInputStream(inputStream); try { buf.Read(contents); buf.Close(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } } catch (Java.IO.FileNotFoundException e) { e.PrintStackTrace(); } return(contents); }
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); // Deixa a imagem disponível na galeria de imagens Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); Android.Net.Uri contentUri = Android.Net.Uri.FromFile(ImageData.Arquivo); mediaScanIntent.SetData(contentUri); SendBroadcast(mediaScanIntent); //Define o tamanho da imagem int height = Resources.DisplayMetrics.HeightPixels; int width = Resources.DisplayMetrics.WidthPixels; //Obtendo dados da imagem var imgFile = new Java.IO.File(ImageData.Arquivo.Path); var stream = new Java.IO.FileInputStream(imgFile); var bytes = new byte[imgFile.Length()]; stream.Read(bytes); MessagingCenter.Send <byte[]>(bytes, "TirarFoto"); // Fazendo dispose da imagem no Java GC.Collect(); }
public Task <FileData> PlatformStopAsync() { if (_recorder == null) { return(Task.FromResult(default(FileData))); } _recorder.Stop(); _recorder.Release(); _recorder = null; Java.IO.File file = new Java.IO.File(_audioFilePath); return(Task.FromResult(new FileData(_audioFilePath, file.Name, (ulong)file.Length()))); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok) { byte[] bytes; using (var stream = new Java.IO.FileInputStream(arquivoImagem)) { bytes = new byte[arquivoImagem.Length()]; stream.Read(bytes); } MessagingCenter.Send <byte[]>(bytes, "FotoTirada"); } }
private static byte[] readFileToByteArray(Java.IO.File file) { FileInputStream fis = null; // Creating a byte array using the length of the file // file.length returns long which is cast to int byte[] bArray = new byte[(int)file.Length()]; try { fis = new FileInputStream(file); fis.Read(bArray); fis.Close(); } catch (Java.IO.IOException ioExp) { ioExp.PrintStackTrace(); } return(bArray); }
/// <summary> /// Read a file with given path and return a byte-array with it's entire contents. /// </summary> public static byte[] ReadAllBytes(string path) { if (path == null) throw new ArgumentNullException("path"); var file = new JFile(path); if (!file.Exists() || !file.IsFile) throw new FileNotFoundException(path); if (!file.CanRead) throw new UnauthorizedAccessException(path); var stream = new FileInputStream(file); try { var array = new byte[file.Length()]; stream.Read(array, 0, array.Length); return array; } finally { stream.Close(); } }
protected async override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Canceled && requestCode == 43) { // Notify user file picking was cancelled. OnDirectoryPickCancelled(); Finish(); } else { System.Diagnostics.Debug.Write(data.Data); try { // read the file out of the cache dir var file = new Java.IO.File(filePath); var fileLength = (int)file.Length(); byte[] fileBytes = new byte[fileLength]; using (var inputStream = new FileInputStream(filePath)) { await inputStream.ReadAsync(fileBytes, 0, fileLength); } // write the file to the path chosen by the user using (var pFD = ContentResolver.OpenFileDescriptor(data.Data, "w")) using (var outputSteam = new FileOutputStream(pFD.FileDescriptor)) { outputSteam.Write(fileBytes); } OnDirectoryPicked(new SavePickerEventArgs(data.Data)); } catch (Exception readEx) { // Notify user file picking failed. OnDirectoryPickError(readEx.Message); System.Diagnostics.Debug.Write(readEx); } finally { Finish(); } } }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); Java.IO.File diretorio = new Java.IO.File( Android.OS.Environment.GetExternalStoragePublicDirectory( Android.OS.Environment.DirectoryPictures), "Imagens"); var resolucaoAntiga = SizeImagem(arquivoImagem.Path); ResizeImage(arquivoImagem.Path, diretorio.Path, 1500, 1200); //var altura = bitmap.Height; //var largura = bitmap.Width; //var Alterada_a_resolução = new System.Drawing.Size((int)bitmap.GetBitmapInfo().Height, (int)bitmap.GetBitmapInfo().Width); //SE TIRAR A FOTO e confirmar if (resultCode == Result.Ok) { byte[] bytes; //Retorna uma stream onde é possivel ler os dados do arquivo using (var stream = new Java.IO.FileInputStream(arquivoImagem)) { //Convertendo a imagem em um array de bytes para usar o array na troca de mensagens com o projeto c# bytes = new byte[arquivoImagem.Length()]; //transferir pro array de bytes o conteudo do arquivo de imagem //stream le os dados do arquivo stream.Read(bytes); } //Arquivo do tipo array de byte[] //instancia de arquivoImagem //Sobrepoe a imagem original no diretorio //envia a msg para a classe masterviewmodel MessagingCenter.Send <byte[]>(bytes, "FotoTirada"); } }
/// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="mirrorNames"></param> /// <param name="mirrorUrls"></param> /// <param name="mirror"></param> /// <param name="title"></param> /// <param name="path">FULL PATH</param> /// <param name="poster"></param> /// <param name="fileName"></param> /// <param name="beforeTxt"></param> /// <param name="openWhenDone"></param> /// <param name="showNotificaion"></param> /// <param name="showDoneNotificaion"></param> /// <param name="showDoneAsToast"></param> /// <param name="resumeIntent"></param> public static void HandleIntent(int id, List <BasicMirrorInfo> mirrors, int mirror, string title, string path, string poster, string beforeTxt, bool openWhenDone, bool showNotificaion, bool showDoneNotificaion, bool showDoneAsToast, bool resumeIntent) { const int UPDATE_TIME = 1; try { isStartProgress[id] = true; print("START DLOAD::: " + id); if (isPaused.ContainsKey(id)) { //if (isPaused[id] == 2) { // isPaused.Remove(id); // print("YEET DELETED KEEEE"); return; // } } var context = Application.Context; //$"{nameof(id)}={id}|||{nameof(title)}={title}|||{nameof(path)}={path}|||{nameof(poster)}={poster}|||{nameof(fileName)}={fileName}|||{nameof(beforeTxt)}={beforeTxt}|||{nameof(openWhenDone)}={openWhenDone}|||{nameof(showDoneNotificaion)}={showDoneNotificaion}|||{nameof(showDoneAsToast)}={showDoneAsToast}|||"); int progress = 0; int bytesPerSec = 0; void UpdateDloadNot(string progressTxt) { //poster != "" if (!isPaused.ContainsKey(id)) { isPaused[id] = 0; } try { int isPause = isPaused[id]; bool canPause = isPause == 0; if (isPause != 2) { ShowLocalNot(new LocalNot() { actions = new List <LocalAction>() { new LocalAction() { action = $"handleDownload|||id={id}|||dType={(canPause ? 1 : 0)}|||", name = canPause ? "Pause" : "Resume" }, new LocalAction() { action = $"handleDownload|||id={id}|||dType=2|||", name = "Stop" } }, mediaStyle = false, bigIcon = poster, title = $"{title} - {ConvertBytesToAny(bytesPerSec / UPDATE_TIME, 2, 2)} MB/s", autoCancel = false, showWhen = false, onGoing = canPause, id = id, smallIcon = PublicNot, progress = progress, body = progressTxt }, context); //canPause } } catch (Exception _ex) { print("ERRORLOADING PROGRESS:::" + _ex); } } void ShowDone(bool succ, string overrideText = null) { print("DAAAAAAAAAASHOW DONE" + succ); if (succ) { App.RemoveKey(DOWNLOAD_KEY, id.ToString()); App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString()); } if (showDoneNotificaion) { print("DAAAAAAAAAASHOW DONE!!!!"); Device.BeginInvokeOnMainThread(() => { try { print("DAAAAAAAAAASHOW DONE222"); ShowLocalNot(new LocalNot() { mediaStyle = poster != "", bigIcon = poster, title = title, autoCancel = true, onGoing = false, id = id, smallIcon = PublicNot, body = overrideText ?? (succ ? "Download done!" : "Download Failed") }, context); // ((e.Cancelled || e.Error != null) ? "Download Failed!" } catch (Exception _ex) { print("SUPERFATALEX: " + _ex); } }); //await Task.Delay(1000); // 100% sure that it is downloaded OnSomeDownloadFinished?.Invoke(null, EventArgs.Empty); } else { print("DONT SHOW WHEN DONE"); } // Toast.MakeText(context, "PG DONE!!!", ToastLength.Long).Show(); } void StartT() { isStartProgress[id] = true; if (isPaused.ContainsKey(id)) { //if (isPaused[id] == 2) { // isPaused.Remove(id); return; // } } Thread t = new Thread(() => { print("START:::"); string json = JsonConvert.SerializeObject(new DownloadHandleNot() { id = id, mirrors = mirrors, showDoneAsToast = showDoneAsToast, openWhenDone = openWhenDone, showDoneNotificaion = showDoneNotificaion, beforeTxt = beforeTxt, mirror = mirror, path = path, poster = poster, showNotificaion = showNotificaion, title = title }); App.SetKey(DOWNLOAD_KEY_INTENT, id.ToString(), json); var mirr = mirrors[mirror]; string url = mirr.mirror; string urlName = mirr.name; string referer = mirr.referer ?? ""; bool isM3u8 = url.Contains(".m3u8"); if ((int)Android.OS.Build.VERSION.SdkInt > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().PermitAll().Build(); StrictMode.SetThreadPolicy(policy); } long total = 0; int fileLength = 0; void UpdateProgress() { UpdateDloadNot($"{beforeTxt.Replace("{name}", urlName)}{progress} % ({ConvertBytesToAny(total, 1, 2)} MB/{ConvertBytesToAny(fileLength, 1, 2)} MB)"); } void UpdateFromId(object sender, int _id) { if (_id == id) { UpdateProgress(); } } bool removeKeys = true; var rFile = new Java.IO.File(path); try { // CREATED DIRECTORY IF NEEDED try { Java.IO.File __file = new Java.IO.File(path); __file.Mkdirs(); } catch (Exception _ex) { print("FAILED:::" + _ex); } URL _url = new URL(url); URLConnection connection = _url.OpenConnection(); print("SET CONNECT ::"); if (!rFile.Exists()) { print("FILE DOSENT EXITS"); rFile.CreateNewFile(); } else { if (resumeIntent) { total = rFile.Length(); connection.SetRequestProperty("Range", "bytes=" + rFile.Length() + "-"); } else { rFile.Delete(); rFile.CreateNewFile(); } } print("SET CONNECT ::2"); connection.SetRequestProperty("Accept-Encoding", "identity"); if (referer != "") { connection.SetRequestProperty("Referer", referer); } int clen = 0; if (isM3u8) { clen = 1; } else { bool Completed = ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(10000), () => { connection.Connect(); clen = connection.ContentLength; if (clen < 5000000 && !path.Contains("/YouTube/")) // min of 5 MB { clen = 0; } }); if (!Completed) { print("FAILED MASS"); clen = 0; } print("SET CONNECT ::3"); } print("TOTALLLLL::: " + clen); if (clen == 0) { if (isStartProgress.ContainsKey(id)) { isStartProgress.Remove(id); } if (mirror < mirrors.Count - 1 && progress < 2 && rFile.Length() < 1000000) // HAVE MIRRORS LEFT { mirror++; removeKeys = false; resumeIntent = false; rFile.Delete(); print("DELETE;;;"); } else { ShowDone(false); } } else { fileLength = clen + (int)total; print("FILELEN:::: " + fileLength); App.SetKey("dlength", "id" + id, fileLength); string fileExtension = MimeTypeMap.GetFileExtensionFromUrl(url); InputStream input = new BufferedInputStream(connection.InputStream); //long skip = App.GetKey<long>(DOWNLOAD_KEY, id.ToString(), 0); OutputStream output = new FileOutputStream(rFile, true); outputStreams[id] = output; inputStreams[id] = input; if (isPaused.ContainsKey(id)) { //if (isPaused[id] == 2) { // isPaused.Remove(id); return; // } } isPaused[id] = 0; activeIds.Add(id); int m3u8Progress = 0; int cProgress() { if (isM3u8) { return(m3u8Progress); } return((int)(total * 100 / fileLength)); } progress = cProgress(); byte[] data = new byte[1024]; // skip; int count; int previousProgress = 0; UpdateDloadNot(total == 0 ? "Download starting" : "Download resuming"); System.DateTime lastUpdateTime = System.DateTime.Now; long lastTotal = total; changedPause += UpdateFromId; if (isStartProgress.ContainsKey(id)) { isStartProgress.Remove(id); } bool showDone = true; bool WriteDataUpdate() { progressDownloads[id] = total; progress = cProgress(); if (isPaused[id] == 1) { print("PAUSEDOWNLOAD"); UpdateProgress(); while (isPaused[id] == 1) { Thread.Sleep(100); } if (isPaused[id] != 2) { UpdateProgress(); } } if (isPaused[id] == 2) // DELETE FILE { print("DOWNLOAD STOPPED"); ShowDone(false, "Download Stopped"); output.Flush(); output.Close(); input.Close(); outputStreams.Remove(id); inputStreams.Remove(id); isPaused.Remove(id); rFile.Delete(); App.RemoveKey(DOWNLOAD_KEY, id.ToString()); App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString()); App.RemoveKey(App.hasDownloadedFolder, id.ToString()); App.RemoveKey("dlength", "id" + id); App.RemoveKey("DownloadIds", id.ToString()); changedPause -= UpdateFromId; activeIds.Remove(id); removeKeys = true; OnSomeDownloadFailed?.Invoke(null, EventArgs.Empty); Thread.Sleep(100); return(true); } if (DateTime.Now.Subtract(lastUpdateTime).TotalSeconds > UPDATE_TIME) { lastUpdateTime = DateTime.Now; long diff = total - lastTotal; // UpdateDloadNot($"{ConvertBytesToAny(diff/UPDATE_TIME, 2,2)}MB/s | {progress}%"); //{ConvertBytesToAny(diff / UPDATE_TIME, 2, 2)}MB/s | if (progress >= 100) { print("DLOADPG DONE!"); ShowDone(true); } else { UpdateProgress(); // UpdateDloadNot(progress + "%"); } bytesPerSec = 0; lastTotal = total; } if (progress >= 100 || progress > previousProgress) { // Only post progress event if we've made progress. previousProgress = progress; if (progress >= 100) { print("DLOADPG DONE!"); ShowDone(true); showDone = false; } else { // UpdateProgress(); // UpdateDloadNot(progress + "%"); } } return(false); } void OnError() { showDone = false; ShowDone(false, "Download Failed"); } if (isM3u8) { var links = ParseM3u8(url, referer); int counter = 0; byte[] buffer; try { while ((buffer = CloudStreamCore.DownloadByteArrayFromUrl(links[counter], referer)) != null) { counter++; m3u8Progress = counter * 100 / links.Length; count = buffer.Length; total += count; bytesPerSec += count; output.Write(buffer, 0, count); if (WriteDataUpdate()) { return; } } } catch (Exception) { OnError(); } } else { try { while ((count = input.Read(data)) != -1) { total += count; bytesPerSec += count; output.Write(data, 0, count); if (WriteDataUpdate()) { return; } } } catch (Exception) { OnError(); } } if (showDone) { ShowDone(true); } output.Flush(); output.Close(); input.Close(); outputStreams.Remove(id); inputStreams.Remove(id); activeIds.Remove(id); } } catch (Exception _ex) { print("DOWNLOADURL: " + url); print("DOWNLOAD FAILED BC: " + _ex); if (mirror < mirrors.Count - 1 && progress < 2) // HAVE MIRRORS LEFT { mirror++; removeKeys = false; resumeIntent = false; rFile.Delete(); } else { ShowDone(false); } } finally { changedPause -= UpdateFromId; isPaused.Remove(id); if (isStartProgress.ContainsKey(id)) { isStartProgress.Remove(id); } if (removeKeys) { //App.RemoveKey(DOWNLOAD_KEY, id.ToString()); //App.RemoveKey(DOWNLOAD_KEY_INTENT, id.ToString()); } else { StartT(); } } }); t.Start(); } StartT(); } catch (Exception) { } }
//TERMINA PROCESAR IMAGENES public static byte[] PathToByte2(string path){ //byte[] pathData=null; Log.Debug ("ImageToByte", "Inicia path to byte"); Log.Debug ("ImageToByte", "Se crea el nuevo file"); var imgFile = new Java.IO.File(path); Log.Debug ("ImageToByte", "Se crea el nuevo stream"); var stream = new Java.IO.FileInputStream(imgFile); Log.Debug ("ImageToByte", "Se Crea el archivo Byte"); var bytes = new byte[imgFile.Length()]; Log.Debug ("ImageToByte", "Se hace el Stream Read"); stream.Read(bytes); stream.Close (); stream.Dispose (); return bytes; }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Init(Context context, string cdn = null, string downloadTitle = null, string downloadMessage = null) { if (_initialized) { return; } var filesDir = context.FilesDir; _ffmpegFile = new Java.IO.File(filesDir + "/ffmpeg"); if (_ffmpegFile.Exists() && _ffmpegFile.CanExecute()) { _initialized = true; return; } copyAssets(context); if (_ffmpegFile.Exists()) { _initialized = true; } return; if (cdn != null) { CDNHost = cdn; } // do all initialization... _ffmpegFile = new Java.IO.File(filesDir + "/ffmpeg"); FFMpegSource source = FFMpegSource.Get(); await Task.Run(() => { if (_ffmpegFile.Exists() && _ffmpegFile.Length() > 15413150) { try { //if (source.IsHashMatch(System.IO.File.ReadAllBytes(_ffmpegFile.CanonicalPath))) { if (!_ffmpegFile.CanExecute()) { _ffmpegFile.SetExecutable(true); } _initialized = true; return; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($" Error validating file {ex}"); } // file is not same... // delete the file... if (_ffmpegFile.CanExecute()) { _ffmpegFile.SetExecutable(false); } _ffmpegFile.Delete(); System.Diagnostics.Debug.WriteLine($"ffmpeg file deleted at {_ffmpegFile.AbsolutePath}"); } }); if (_initialized) { // ffmpeg file exists... return; } if (_ffmpegFile.Exists()) { _ffmpegFile.Delete(); } // lets try to download var dialog = new ProgressDialog(context); dialog.SetTitle(downloadMessage ?? "Downloading Video Converter"); //dlg.SetMessage(downloadMessage ?? "Downloading Video Converter"); dialog.Indeterminate = false; dialog.SetProgressStyle(ProgressDialogStyle.Horizontal); dialog.SetCancelable(false); dialog.CancelEvent += (s, e) => { }; dialog.SetCanceledOnTouchOutside(false); dialog.Show(); using (var c = new System.Net.Http.HttpClient()) { using (var fout = System.IO.File.OpenWrite(_ffmpegFile.AbsolutePath)) { string url = source.Url; var g = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url); var h = await c.SendAsync(g, System.Net.Http.HttpCompletionOption.ResponseHeadersRead); var buffer = new byte[51200]; var s = await h.Content.ReadAsStreamAsync(); long total = h.Content.Headers.ContentLength.GetValueOrDefault(); IEnumerable <string> sl; if (h.Headers.TryGetValues("Content-Length", out sl)) { if (total == 0 && sl.Any()) { long.TryParse(sl.FirstOrDefault(), out total); } } int count = 0; int progress = 0; dialog.Max = (int)total; while ((count = await s.ReadAsync(buffer, 0, buffer.Length)) > 0) { await fout.WriteAsync(buffer, 0, count); progress += count; //System.Diagnostics.Debug.WriteLine($"Downloaded {progress} of {total} from {url}"); dialog.Progress = progress; } dialog.Hide(); } } System.Diagnostics.Debug.WriteLine($"ffmpeg file copied at {_ffmpegFile.AbsolutePath}"); if (!_ffmpegFile.CanExecute()) { _ffmpegFile.SetExecutable(true); System.Diagnostics.Debug.WriteLine($"ffmpeg file made executable"); } _initialized = true; }