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); }
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); } }
protected JsonObject ParseURL(string urlstring) { Log.Debug(TAG, "Parse URL: " + urlstring); InputStream inputStream = null; mPrefixUrl = mContext.Resources.GetString(Resource.String.prefix_url); try { Java.Net.URL url = new Java.Net.URL(urlstring); var urlConnection = url.OpenConnection(); inputStream = new BufferedInputStream(urlConnection.InputStream); var reader = new BufferedReader(new InputStreamReader( urlConnection.InputStream, "iso-8859-1"), 8); var sb = new StringBuilder(); string line = null; while ((line = reader.ReadLine()) != null) { sb.Append(line); } var json = sb.ToString(); return((JsonObject)JsonObject.Parse(json)); } catch (Exception e) { Log.Debug(TAG, "Failed to parse the json for media list", e); return(null); } finally { if (null != inputStream) { try { inputStream.Close(); } catch (IOException e) { Log.Debug(TAG, "Json feed closed", e); } } } }
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); }
/// <summary> /// 解压文件 /// </summary> /// <param name="inputZip"></param> /// <param name="destinationDirectory"></param> public static void UnzipFile(string inputZip, string destinationDirectory) { int buffer = 2048; List <string> zipFiles = new List <string>(); File sourceZipFile = new File(inputZip); File unzipDirectory = new File(destinationDirectory); CreateDir(unzipDirectory.AbsolutePath); ZipFile zipFile; zipFile = new ZipFile(sourceZipFile, ZipFile.OpenRead); IEnumeration zipFileEntries = zipFile.Entries(); while (zipFileEntries.HasMoreElements) { ZipEntry entry = (ZipEntry)zipFileEntries.NextElement(); string currentEntry = entry.Name; File destFile = new File(unzipDirectory, currentEntry); if (currentEntry.EndsWith(Constant.SUFFIX_ZIP)) { zipFiles.Add(destFile.AbsolutePath); } File destinationParent = destFile.ParentFile; CreateDir(destinationParent.AbsolutePath); if (!entry.IsDirectory) { if (destFile != null && destFile.Exists()) { continue; } BufferedInputStream inputStream = new BufferedInputStream(zipFile.GetInputStream(entry)); int currentByte; // buffer for writing file byte[] data = new byte[buffer]; var fos = new System.IO.FileStream(destFile.AbsolutePath, System.IO.FileMode.OpenOrCreate); BufferedOutputStream dest = new BufferedOutputStream(fos, buffer); while ((currentByte = inputStream.Read(data, 0, buffer)) != -1) { dest.Write(data, 0, currentByte); } dest.Flush(); dest.Close(); inputStream.Close(); } } zipFile.Close(); foreach (var zipName in zipFiles) { UnzipFile(zipName, destinationDirectory + File.SeparatorChar + zipName.Substring(0, zipName.LastIndexOf(Constant.SUFFIX_ZIP))); } }
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); }
protected MovieJson[] ParseURL(string urlstring) { Log.Debug(TAG, "Parse URL: " + urlstring); InputStream inputStream = null; try { Java.Net.URL url = new Java.Net.URL(urlstring); var urlConnection = url.OpenConnection(); inputStream = new BufferedInputStream(urlConnection.InputStream); var reader = new BufferedReader(new InputStreamReader( urlConnection.InputStream, "iso-8859-1"), 8); var sb = new StringBuilder(); string line = null; while ((line = reader.ReadLine()) != null) { sb.Append(line); } var json = sb.ToString(); var response = JsonConvert.DeserializeObject <MoviesResponse> (json); return(response.Results); } catch (Exception e) { Log.Debug(TAG, "Failed to parse the json for media list", e); return(null); } finally { if (null != inputStream) { try { inputStream.Close(); } catch (IOException e) { Log.Debug(TAG, "Json feed closed", e); } } } }
//*************************************************************************************************** //******************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 static void startReplay(string filename) { if (captureInProgress) { VideoEngine.log_Renamed.error("Ignoring startReplay, capture is in progress"); return; } VideoEngine.log_Renamed.info("Starting replay: " + filename); try { System.IO.Stream @in = new BufferedInputStream(new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read)); while (@in.available() > 0) { CaptureHeader header = CaptureHeader.read(@in); int packetType = header.PacketType; switch (packetType) { case CaptureHeader.PACKET_TYPE_LIST: CaptureList list = CaptureList.read(@in); list.commit(); break; case CaptureHeader.PACKET_TYPE_RAM: CaptureRAM ramFragment = CaptureRAM.read(@in); ramFragment.commit(); break; // deprecated case CaptureHeader.PACKET_TYPE_DISPLAY_DETAILS: CaptureDisplayDetails displayDetails = CaptureDisplayDetails.read(@in); displayDetails.commit(); break; case CaptureHeader.PACKET_TYPE_FRAMEBUF_DETAILS: // don't replay this one immediately, wait until after the list has finished executing replayFrameBufDetails = CaptureFrameBufDetails.read(@in); break; default: throw new Exception("Unknown packet type " + packetType); } } @in.Close(); } catch (Exception e) { VideoEngine.log_Renamed.error("Failed to start replay: " + e.Message); Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); } }
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); }
/// <summary>read</summary> /// <exception cref="System.Exception"/> public virtual void Read(File file, PDXReaderListener pdxReaderListener) { try { /* * start */ pdxReaderListener.Start(); /* * set up streams */ BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream (file)); LittleEndianDataInputStream littleEndianDataInputStream = new LittleEndianDataInputStream (bufferedInputStream); try { /* * mark and read the headers */ bufferedInputStream.Mark(MaxHeaderSize); ReadHeaders(littleEndianDataInputStream); /* * call the api */ pdxReaderListener.Header(dbTableHeader); /* * read the block data */ bufferedInputStream.Reset(); ReadBlocks(bufferedInputStream, pdxReaderListener); /* * done */ pdxReaderListener.Finish(); } finally { littleEndianDataInputStream.Close(); bufferedInputStream.Close(); } } catch (Exception e) { throw new Exception("Exception in read", e); } }
/// <exception cref="System.IO.IOException"></exception> protected virtual void Copy(IInputStream rawin, Socket4Adapter sock, bool update) { var @in = new BufferedInputStream(rawin); var buffer = new byte[BlobImpl.CopybufferLength]; var bytesread = -1; while ((bytesread = rawin.Read(buffer)) >= 0) { sock.Write(buffer, 0, bytesread); if (update) { _currentByte += bytesread; } } @in.Close(); }
//import eu.europa.ec.markt.dss.validation.asic.ASiCXMLDocumentValidator; //import eu.europa.ec.markt.dss.validation.pades.PDFDocumentValidator; //import eu.europa.ec.markt.dss.validation.xades.XMLDocumentValidator; /// <summary>Guess the document format and return an appropriate document</summary> /// <param name="document"></param> /// <returns></returns> /// <exception cref="System.IO.IOException"></exception> public static SignedDocumentValidator FromDocument(Document document) { InputStream input = null; try { input = new BufferedInputStream(document.OpenStream()); input.Mark(5); byte[] preamble = new byte[5]; int read = input.Read(preamble); input.Reset(); if (read < 5) { throw new RuntimeException("Not a signed document"); } string preambleString = Sharpen.Runtime.GetStringForBytes(preamble); if (Sharpen.Runtime.GetBytesForString(preambleString)[0] == unchecked ((int)(0x30) )) { try { return(new CMSDocumentValidator(document)); } catch (CmsException) { throw new IOException("Not a valid CAdES file"); } } else { throw new RuntimeException("Document format not recognized/handled"); } } finally { if (input != null) { try { input.Close(); } catch (IOException) { } } } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: protected java.awt.image.System.Drawing.Bitmap readBmp(java.io.File imageFile) throws java.io.IOException protected internal virtual System.Drawing.Bitmap readBmp(File imageFile) { System.IO.Stream @is = new BufferedInputStream(new System.IO.FileStream(imageFile, System.IO.FileMode.Open, System.IO.FileAccess.Read)); // Reading file header int magic = readLittleEndianShort(@is); int fileSize = readLittleEndianInt(@is); @is.skip(4); int dataOffset = readLittleEndianInt(@is); // Reading DIB header int dibHeaderLength = readLittleEndianInt(@is); int imageWidth = readLittleEndianInt(@is); int imageHeight = readLittleEndianInt(@is); int numberPlanes = readLittleEndianShort(@is); int bitsPerPixel = readLittleEndianShort(@is); // Skip rest of DIB header until data start @is.skip(dataOffset - 14 - 16); System.Drawing.Bitmap img = null; if (magic == (('M' << 8) | 'B') && dibHeaderLength >= 16 && fileSize >= dataOffset && numberPlanes == 1 && bitsPerPixel == 32) { img = new System.Drawing.Bitmap(imageWidth, imageHeight, System.Drawing.Bitmap.TYPE_INT_ARGB); for (int y = imageHeight - 1; y >= 0; y--) { for (int x = 0; x < imageWidth; x++) { int argb = readLittleEndianInt(@is); img.setRGB(x, y, argb); } } } @is.Close(); return(img); }
/// <summary>Read all blocks</summary> /// <exception cref="Com.Khubla.Pdxreader.Api.PDXReaderException"/> private void ReadBlocks(File file) { try { foreach (MBTableBlock mbTableBlock in blocks) { /* * set up streams */ BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream (file)); LittleEndianDataInputStream littleEndianDataInputStream = new LittleEndianDataInputStream (bufferedInputStream); try { /* * ffd */ long skipped = littleEndianDataInputStream.Skip(mbTableBlock.GetFileOffset()); if (0 != skipped) { /* * read */ mbTableBlock.Read(littleEndianDataInputStream); } } finally { littleEndianDataInputStream.Close(); bufferedInputStream.Close(); } } } catch (Exception e) { throw new PDXReaderException("Exception in read", e); } }
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); } }
private static void FileToZip(File file, ZipOutputStream outputStream) { BufferedInputStream origin = null; try { var buffer = 2048; var data = new byte[buffer]; var fi = new FileStream(file.AbsolutePath, FileMode.Open); origin = new BufferedInputStream(fi, buffer); var entry = new ZipEntry(file.Name); outputStream.PutNextEntry(entry); int count; while ((count = origin.Read(data, 0, buffer)) != -1) { outputStream.Write(data, 0, count); } } finally { origin?.Close(); } }
/** * 扫描添加文件Entry * * @param base 基路径 * @param source 源文件 * @param zos Zip文件输出流 * @throws IOException */ private static void addEntry(string bbase, File source, ZipOutputStream zos) { // 按目录分级,形如:/aaa/bbb.txt string entry = bbase + source.Name; if (source.IsDirectory) { foreach (File file in source.ListFiles()) { // 递归列出目录下的所有文件,添加文件Entry addEntry(entry + "/", file, zos); } } else { System.IO.FileStream fis = null; BufferedInputStream bis = null; try { byte[] buffer = new byte[1024 * 10]; fis = new System.IO.FileStream(source.Path, System.IO.FileMode.Append); bis = new BufferedInputStream(fis, buffer.Length); int read = 0; zos.PutNextEntry(new ZipEntry(entry)); while ((read = bis.Read(buffer, 0, buffer.Length)) != -1) { zos.Write(buffer, 0, read); } zos.CloseEntry(); } finally { bis.Close(); fis.Close(); } } }
/// <summary>read</summary> /// <exception cref="Com.Khubla.Pdxreader.Api.PDXReaderException"/> public virtual void Read(File file) { try { /* * set up streams */ BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream (file)); LittleEndianDataInputStream littleEndianDataInputStream = new LittleEndianDataInputStream (bufferedInputStream); try { /* * mark and read the headers */ bufferedInputStream.Mark(MaxHeaderSize); ReadHeaders(littleEndianDataInputStream); /* * read the block data */ bufferedInputStream.Reset(); ReadBlocks(bufferedInputStream); } finally { littleEndianDataInputStream.Close(); bufferedInputStream.Close(); } } catch (Exception e) { throw new PDXReaderException("Exception in read", e); } }
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; } }
protected JsonObject ParseURL (string urlstring) { Log.Debug (TAG, "Parse URL: " + urlstring); InputStream inputStream = null; mPrefixUrl = mContext.Resources.GetString (Resource.String.prefix_url); try { Java.Net.URL url = new Java.Net.URL (urlstring); var urlConnection = url.OpenConnection (); inputStream = new BufferedInputStream (urlConnection.InputStream); var reader = new BufferedReader (new InputStreamReader ( urlConnection.InputStream, "iso-8859-1"), 8); var sb = new StringBuilder (); string line = null; while ((line = reader.ReadLine ()) != null) { sb.Append (line); } var json = sb.ToString (); return (JsonObject)JsonObject.Parse (json); } catch (Exception e) { Log.Debug (TAG, "Failed to parse the json for media list", e); return null; } finally { if (null != inputStream) { try { inputStream.Close (); } catch (IOException e) { Log.Debug (TAG, "Json feed closed", e); } } } }
public static string getCharset(string fileName) { BufferedInputStream bis = null; string charset = "GBK"; byte[] first3Bytes = new byte[3]; try { bool check = false; bis = new BufferedInputStream(new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate)); bis.Mark(0); int read = bis.Read(first3Bytes, 0, 3); if (read == -1) { return(charset); } if (first3Bytes[0] == (byte)0xFF && first3Bytes[1] == (byte)0xFE) { charset = "UTF-16LE"; check = true; } else if (first3Bytes[0] == (byte)0xFE && first3Bytes[1] == (byte)0xFF) { charset = "UTF-16BE"; check = true; } else if (first3Bytes[0] == (byte)0xEF && first3Bytes[1] == (byte)0xBB && first3Bytes[2] == (byte)0xBF) { charset = "UTF-8"; check = true; } bis.Mark(0); if (!check) { while ((read = bis.Read()) != -1) { if (read >= 0xF0) { break; } if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBK { break; } if (0xC0 <= read && read <= 0xDF) { read = bis.Read(); if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF) // (0x80 - 0xBF),也可能在GB编码内 { continue; } else { break; } } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小 read = bis.Read(); if (0x80 <= read && read <= 0xBF) { read = bis.Read(); if (0x80 <= read && read <= 0xBF) { charset = "UTF-8"; break; } else { break; } } else { break; } } } } } catch (Exception e) { e.PrintStackTrace(); } finally { if (bis != null) { try { bis.Close(); } catch (IOException e) { e.PrintStackTrace(); } } } return(charset); }
public void zip() { System.IO.FileStream dest = null; ZipOutputStream out_ = null; try { dest = new System.IO.FileStream(_zipFile, System.IO.FileMode.Create); out_ = new ZipOutputStream(new System.IO.BufferedStream(dest)); byte[] data = new byte[BUFFER]; for (int i = 0; i < _files.Length; i++) { System.IO.FileStream fi = null; BufferedInputStream origin = null; try { fi = new System.IO.FileStream(_files[i], System.IO.FileMode.Open); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(Path.GetFileName(_files[i])); out_.PutNextEntry(entry); int count; //for (int b = origin.Read(); b != -1; b = origin.Read()) //{ // out_.Write(b); //} while ((count = origin.Read(data, 0, BUFFER)) != -1) { out_.Write(data, 0, count); } } finally { if (origin != null) { origin.Close(); } if (fi != null) { fi.Close(); } } } } finally { if (out_ != null) { out_.Close(); //top first } if (dest != null) { dest.Close(); } } }
/// <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) { } }
/// <summary>This method finds all the blocks with their types and offsets</summary> /// <exception cref="Com.Khubla.Pdxreader.Api.PDXReaderException"/> private void PreReadBlocks(File file) { try { /* * set up streams */ BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream (file)); LittleEndianDataInputStream littleEndianDataInputStream = new LittleEndianDataInputStream (bufferedInputStream); try { /* * offset tracker */ int fileOffset = 0; /* * loop */ while (littleEndianDataInputStream.Available() > 1) { /* * read type */ int type = littleEndianDataInputStream.ReadByte(); /* * get an appropriate Block type */ MBTableBlock.RecordType recordType = MBTableBlock.GetRecordType(type); /* * ok? */ if (null != recordType) { MBTableBlock mbTableBlock = MBTableBlockFactory.GetMBTableBlock(recordType); /* * set the offset */ mbTableBlock.SetFileOffset(fileOffset); /* * pre-read */ int bytesPreRead = mbTableBlock.PreRead(littleEndianDataInputStream); /* * add to list */ blocks.Add(mbTableBlock); /* * skip forward to next one */ int bytesToSkip = mbTableBlock.GetSizeofBlock() - (1 + bytesPreRead); long skipped = littleEndianDataInputStream.Skip(bytesToSkip); if (0 != skipped) { /* * update the offset */ fileOffset += mbTableBlock.GetSizeofBlock(); } } } } finally { littleEndianDataInputStream.Close(); bufferedInputStream.Close(); } } catch (Exception e) { throw new PDXReaderException("Exception in read", e); } }
//*************************************************************************************************** //******************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)); }