Exemplo n.º 1
0
        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"));
            }
        }
Exemplo n.º 2
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult (requestCode, resultCode, data);

            if (resultCode == Result.Ok) {
                if (requestCode == 0)
                {
                    _photoAdapter.NotifyDataSetChanged ();
                    System.Console.Out.WriteLine (_temp_IMG_List.Count);
                }

                if (requestCode == 1)
                {
                    _temp_IMG_List.RemoveAt(int.Parse(data.GetStringExtra("delete")));
                    _photoAdapter.NotifyDataSetChanged ();
                    //System.Console.Out.WriteLine ("delete "  + data.GetStringExtra("delete"));
                }
            }
            if (resultCode == Result.Canceled)
            {
                if (requestCode == 0)
                {
                    var deleteFile = new Java.IO.File (_temp_IMG_List [_temp_IMG_List.Count - 1].Path);
                    deleteFile.Delete ();
                    _temp_IMG_List.RemoveAt (_temp_IMG_List.Count-1);
                    _photoAdapter.NotifyDataSetChanged ();

                }
            }
        }
Exemplo n.º 3
0
        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();
            }
        }
Exemplo n.º 4
0
        private void FileDelete()
        {
            Java.IO.File    file   = this.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads);
            IFilenameFilter filter = new AutoUpdateFileFilter();

            Java.IO.File[] files = file.ListFiles(filter);

            if (files != null && files.Length > 0)
            {
                foreach (var item in files)
                {
                    if (item.IsFile)
                    {
                        if (item.Name.ToString().StartsWith(Application.Context.PackageName))
                        {
                            using (Java.IO.File fileDel = new Java.IO.File(item.ToString()))
                            {
                                if (fileDel.Exists())
                                {
                                    fileDel.Delete();
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        private bool DeleteDirectory(File file)
        {
            int size = file.ListFiles().Length;

            if (size > 0)
            {
                foreach (var VARIABLE in file.ListFiles())
                {
                    if (VARIABLE.IsDirectory)
                    {
                        DeleteDirectory(VARIABLE);
                    }

                    else
                    {
                        File temp = VARIABLE;

                        temp.Delete();
                    }
                }
            }
            File t = file;

            return(t.Delete());
        }
        private void PlayRecording(object sender, EventArgs e)
        {
            Label l = (Label)sender;

            Java.IO.File       tempFile = Java.IO.File.CreateTempFile($"{l.Text}", ".mp3");
            Models.AudioRecord ar       = (Models.AudioRecord)l.BindingContext;

            if (!mp.IsPlaying)
            {
                FileOutputStream fos = new Java.IO.FileOutputStream(tempFile);
                fos.Write(ar.AudioClip);
                fos.Close();

                mp.Reset();
                //string path = $"{Android.OS.Environment.ExternalStorageDirectory.AbsolutePath}/{l.Text}.mp3";
                Java.IO.FileInputStream fis = new Java.IO.FileInputStream(tempFile);
                mp.SetDataSource(fis.FD);
                mp.Prepare();
                mp.Start();
            }
            else
            {
                mp.Stop();
                mp.Release();
                tempFile.Delete();
            }
        }
Exemplo n.º 7
0
 private static bool DeleteFolderRecursively(Java.IO.File file)
 {
     try
     {
         bool res = true;
         foreach (Java.IO.File childFile in file.ListFiles())
         {
             if (childFile.IsDirectory)
             {
                 res &= DeleteFolderRecursively(childFile);
             }
             else
             {
                 res &= childFile.Delete();
             }
         }
         res &= file.Delete();
         return(res);
     }
     catch (Java.Lang.Exception e)
     {
         e.PrintStackTrace();
         return(false);
     }
 }
Exemplo n.º 8
0
        public void SaveCurrentData(Context context)
        {
            try
            {
                var file = new File(context.FilesDir, Constants.MedicationFile);
                var data = new JSONArray();

                if (DiseaseList.Count == 0)
                {
                    file.Delete();
                    file = new File(context.FilesDir, Constants.MedicationFile);
                }

                for (var i = 0; i < DiseaseList.Count; i++)
                {
                    data.Put(CreateJsonObject(DiseaseList[i]));
                }

                var fileWriter        = new FileWriter(file);
                var outBufferedWriter = new BufferedWriter(fileWriter);
                outBufferedWriter.Write(data.ToString());
                outBufferedWriter.Close();
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
            }
        }
Exemplo n.º 9
0
        public bool deleteFile(string path)
        {
            Java.IO.File file    = new Java.IO.File(path);
            bool         deleted = file.Delete();

            return(deleted);
        }
        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 void DeleteTempFile()
        {
            WvlLogger.Log(LogType.TraceAll, "DeleteTempFile()");
            Java.IO.File file = new Java.IO.File(GetTempFilename());

            file.Delete();
        }
Exemplo n.º 12
0
        public async Task View(Stream stream, string filename)
        {
            if ((int)Android.OS.Build.VERSION.SdkInt >= 23)
            {
                bool result = await PermissionsHelper.RequestStorrageAccess();

                if (!result)
                {
                    return;
                }
            }

            string root = null;

            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.App.Application.Context.GetExternalFilesDir(null).ToString();
            }
            else
            {
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }

            Java.IO.File myDir = new Java.IO.File(root + "/Telerik");
            myDir.Mkdir();
            Java.IO.File file = new Java.IO.File(myDir, filename);

            if (file.Exists())
            {
                file.Delete();
            }

            using (FileOutputStream outs = new FileOutputStream(file))
            {
                stream.Seek(0, SeekOrigin.Begin);
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                outs.Write(buffer);
            }

            if (file.Exists())
            {
                var             context = Android.App.Application.Context;
                Android.Net.Uri path    = AndroidX.Core.Content.FileProvider.GetUriForFile(context, "SDKBrowser.Android.fileprovider", 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);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);

                var chooser = Intent.CreateChooser(intent, "Choose App");
                chooser.SetFlags(ActivityFlags.NewTask);
                chooser.AddFlags(ActivityFlags.GrantReadUriPermission);
                context.StartActivity(chooser);
            }

            return;
        }
Exemplo n.º 13
0
 public void CleanFile()
 {
     Java.IO.File file = new Java.IO.File(filePath);
     if (file != null)
     {
         file.Delete();
     }
 }
Exemplo n.º 14
0
        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");
                //
            }
        }
        private void deleteRecursive(Java.IO.File fileOrDirectory)
        {
            if (fileOrDirectory.IsDirectory)
            {
                fileOrDirectory.ListFiles().ToList().ForEach(f => deleteRecursive(f));
            }

            fileOrDirectory.Delete();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Delete the file with the given path.
        /// </summary>
        public static void Delete(string path)
        {
            var file = new JFile(path);

            if (file.IsFile)
            {
                file.Delete();
            }
        }
Exemplo n.º 18
0
        private void delete_pic()
        {
            Java.IO.File fis = new Java.IO.File(absolut_path_pic);


            if (fis.Exists())
            {
                fis.Delete();
            }
        }
        private void removeTempFiles()
        {
            var d = new Java.IO.File(destinationdir);

            deleteRecursive(d);

            var zipFile = new Java.IO.File(visualization);

            zipFile.Delete();
        }
Exemplo n.º 20
0
        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));
                }
            }
        }
Exemplo n.º 21
0
        /// <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);
            }
        }
Exemplo n.º 22
0
 public static void deleteDownloadedFile(Context context)
 {
     Java.IO.File file = new Java.IO.File(getFilePath(context));
     if (null != file & file.Exists())
     {
         if (file.Delete())
         {
             ;
         }
     }
 }
Exemplo n.º 23
0
        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()
Exemplo n.º 24
0
        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"));
            }
        }
Exemplo n.º 25
0
        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);
            }
        }
Exemplo n.º 26
0
        public void decrypt(string filename)
        {
            try
            {
                Java.IO.File extStore = new Java.IO.File("/storage/emulated/0/jukebox/Songs");
                Android.Util.Log.Error("Decryption Started", extStore + "");
                FileInputStream fis = new FileInputStream(extStore + "/" + filename + ".aes");

                createFile(filename, extStore);
                FileOutputStream     fos = new FileOutputStream(extStore + "/" + "decrypted" + filename, false);
                System.IO.FileStream fs  = System.IO.File.OpenWrite(extStore + "/" + "decrypted" + filename);
                // Create cipher

                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.DecryptMode, skeySpec, iv);

                startTime = System.DateTime.Now.Millisecond;
                CipherOutputStream cos  = new CipherOutputStream(fs, cipher);
                Java.IO.File       file = new Java.IO.File("/storage/emulated/0/jukebox/Songs" + "/" + filename);
                if (file.Delete())
                {
                    Android.Util.Log.Error("File Deteted", extStore + filename);
                }
                else
                {
                    Android.Util.Log.Error("File Doesn't exists", extStore + filename);
                }

                int    b;
                byte[] d = new byte[1024 * 1024];
                while ((b = fis.Read(d)) != -1)
                {
                    cos.Write(d, 0, b);
                }

                stopTime = System.DateTime.Now.Millisecond;

                Android.Util.Log.Error("Decryption Ended", extStore + "/" + "decrypted" + filename);
                Android.Util.Log.Error("Time Elapsed", ((stopTime - startTime) / 1000.0) + "");

                cos.Flush();
                cos.Close();
                fis.Close();
            }
            catch (Exception e)
            {
                Android.Util.Log.Error("lv", e.Message);
            }
        }
Exemplo n.º 27
0
    //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"));
        }
    }
Exemplo n.º 28
0
            private async void CreatePDF2(Android.Webkit.WebView webview)
            {
                try
                {
                    // 计算webview打印需要的页数
                    int numberOfPages = await GetPDFPageCount(webview);

                    File pdfFile = new File(fileNameWithPath);
                    if (pdfFile.Exists())
                    {
                        pdfFile.Delete();
                    }
                    pdfFile.CreateNewFile();
                    descriptor = ParcelFileDescriptor.Open(pdfFile, ParcelFileMode.ReadWrite);
                    // 设置打印参数
                    var             dm         = webview.Context.Resources.DisplayMetrics;
                    var             d          = dm.Density;
                    var             dpi        = dm.DensityDpi;
                    var             height     = dm.HeightPixels;
                    var             width      = dm.WidthPixels;
                    var             xdpi       = dm.Xdpi;
                    var             ydpi       = dm.Ydpi;
                    PrintAttributes attributes = new PrintAttributes.Builder()
                                                 .SetMediaSize(MediaSize)
                                                 .SetResolution(new PrintAttributes.Resolution("id", Context.PrintService, Convert.ToInt16(xdpi), Convert.ToInt16(ydpi)))
                                                 .SetColorMode(PrintColorMode.Color)
                                                 .SetMinMargins(PrintAttributes.Margins.NoMargins)
                                                 .Build();

                    ranges = new PageRange[] { new PageRange(0, numberOfPages - 1) };
                    // 创建pdf文件缓存目录
                    // 获取需要打印的webview适配器
                    printAdapter = webview.CreatePrintDocumentAdapter("CreatePDF");
                    // 开始打印
                    printAdapter.OnStart();
                    printAdapter.OnLayout(attributes, attributes, new CancellationSignal(), GetLayoutResultCallback(this), new Bundle());
                }
                catch (Java.IO.FileNotFoundException e)
                {
                    System.Console.WriteLine(e.Message);
                }
                catch (Java.IO.IOException e)
                {
                    System.Console.WriteLine(e.Message);
                }
                catch (Java.Lang.Exception e)
                {
                    System.Console.WriteLine(e.Message);
                }
            }
Exemplo n.º 29
0
 public static void ClearFile()
 {
     Java.IO.File file2 = new Java.IO.File(PATH);
     if (file2.Exists())
     {
         try
         {
             file2.Delete();
             // file2.Mkdirs();//.CreateNewFile();
         }
         catch (System.IO.IOException e)
         {
         }
     }
 }
Exemplo n.º 30
0
    //Method to save document as a file in Android and view the saved document
    public string 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 = 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();
        Android.Net.Uri path = null;
        //Invoke the created file for viewing
        if (file.Exists())
        {
            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, "Elija una aplicación"));*/
        }

        return(path.Path);
    }
Exemplo n.º 31
0
    //Method to save document as a file in Android and view the saved document
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
    public async Task SaveAndView(string fileName, String contentType, MemoryStream stream)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
    {
        string root = null;

        //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);
        }
        string documentsPath = Environment.CurrentDirectory;

        //Create directory and file
        Application.Current.Properties["savename"] = root + "/GreenBankX";
        Java.IO.File myDir = new Java.IO.File(root + "/GreenBankX");
        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"));
        }
    }
Exemplo n.º 32
0
        //Method to save document as a file in Android and view the saved document
        public void SaveAndView(string fileName, String contentType, MemoryStream stream, Akcje activity)
        {
            string root = null;

            //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())
            {
                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.AddFlags(ActivityFlags.NewTask);
                intent.SetDataAndType(path, mimeType);
                //intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                activity.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            }
        }
Exemplo n.º 33
0
        public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream filestream)
        {
            string exception = string.Empty;
            string root      = null;

            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(filestream.ToArray());

                outs.Flush();
                outs.Close();
            }
            catch (Exception e)
            {
                exception = e.ToString();
            }

            Intent email = new Intent(Android.Content.Intent.ActionSend);
            var    uri   = FileProvider.GetUriForFile(this.m_context, Application.Context.PackageName + ".provider", file);

            //file.SetReadable(true, true);
            email.PutExtra(Android.Content.Intent.ExtraSubject, subject);
            email.PutExtra(Intent.ExtraStream, uri);
            email.SetType("application/pdf");

            MainActivity.BaseActivity.StartActivity(email);
        }
Exemplo n.º 34
0
        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"));

            }
        }
Exemplo n.º 35
0
 /// <summary>
 /// Delete the file with the given path.
 /// </summary>
 public static void Delete(string path)
 {
     var file = new JFile(path);
     if (file.IsFile)
         file.Delete();
 }
		public  MemoryStream CompressVideo( string sourceFilePath, string destinationFilePath, bool deleteSourceFile )
		{
			if (sourceFilePath == null || destinationFilePath == null)
				return null;

			MediaMetadataRetriever media = new MediaMetadataRetriever ();
			media.SetDataSource ( sourceFilePath );
			string videoRotation = media.ExtractMetadata ( MetadataKey.VideoRotation );


			XamarinAndroidFFmpeg.FFMpeg ffmpeg = new FFMpeg ( MainApplication.Context, App.DownloadsPath);
			var onComplete = new MyCommand ((_) => 
				{
					
				});

			var onMessage = new MyCommand ((message) => 
				{
					System.Diagnostics.Debug.WriteLine(  "---" + message);
				});


			if (videoRotation != null && videoRotation == "90")
			{
				string[] cmds = new string[] 
				{
					"-i",
					sourceFilePath,
					"-vcodec",
					"mpeg4",
					"-acodec",
					"aac",
					"-strict",
					"-2",
					"-ac",
					"1",
					"-ar",
					"16000",
					"-r",
					"13",
					"-ab",
					"32000",
					"-vf",
					"transpose=1",
					"-y",
					destinationFilePath
				};
				var callbacks = new FFMpegCallbacks (onComplete, onMessage);
				ffmpeg.Execute (cmds, callbacks);
			} 
			else 
			{
				string[] cmds = new string[] 
				{
					"-i",
					sourceFilePath,
					"-vcodec",
					"mpeg4",
					"-acodec",
					"aac",
					"-strict",
					"-2",
					"-ac",
					"1",
					"-ar",
					"16000",
					"-r",
					"13",
					"-ab",
					"32000",
					"-y",
					destinationFilePath
				};
				var callbacks = new FFMpegCallbacks (onComplete, onMessage);
				ffmpeg.Execute (cmds, callbacks);
			}
		

			if (deleteSourceFile) 
			{
				Java.IO.File toDel = new Java.IO.File ( sourceFilePath );
				toDel.Delete ();
			}


			MemoryStream ms = new MemoryStream();    
			FileStream file = new FileStream(  destinationFilePath, FileMode.Open, FileAccess.Read);
			file.CopyTo ( ms );
			file.Close();
			return ms;

		}
Exemplo n.º 37
0
        private async Task<string> CopyAssets ()
        {
            try {
                Android.Content.Res.AssetManager assetManager = _context.Assets;
                string[] files = assetManager.List ("tessdata");
                File file = _context.GetExternalFilesDir (null);
                var tessdata = new File (_context.GetExternalFilesDir (null), "tessdata");
                if (!tessdata.Exists ()) {
                    tessdata.Mkdir ();
                } else {
                    var packageInfo = _context.PackageManager.GetPackageInfo (_context.PackageName, 0);
                    var version = packageInfo.VersionName;
                    var versionFile = new File (tessdata, "version");
                    if (versionFile.Exists ()) {
                        var fileVersion = System.IO.File.ReadAllText (versionFile.AbsolutePath);
                        if (version == fileVersion) {
                            Log.Debug ("[TesseractApi]", "Application version didn't change, skipping copying assets");
                            return file.AbsolutePath;
                        }
                        versionFile.Delete ();
                    }
                    System.IO.File.WriteAllText (versionFile.AbsolutePath, version);
                }

                Log.Debug ("[TesseractApi]", "Copy assets to " + file.AbsolutePath);

                foreach (var filename in files) {
                    using (var inStream = assetManager.Open ("tessdata/" + filename)) {
                        var outFile = new File (tessdata, filename);
                        if (outFile.Exists ()) {
                            outFile.Delete ();
                        }
                        using (var outStream = new FileStream (outFile.AbsolutePath, FileMode.Create)) {
                            await inStream.CopyToAsync (outStream);
                            await outStream.FlushAsync ();
                        }
                    }
                }
                return file.AbsolutePath;
            } catch (Exception ex) {
                Log.Error ("[TesseractApi]", ex.Message);
            }
            return null;
        }