Exemplo n.º 1
0
 //метод записи файла
 private void WriteFile(DriveId folderBackUpId, string filename, IDriveApiDriveContentsResult content)
 {
     try
     {
         byte[] bytes = System.IO.File.ReadAllBytes(pathToDb);
         string file  = Convert.ToBase64String(bytes);
         using (var writer = new OutputStreamWriter(content.DriveContents.OutputStream))
         {
             writer.Write(file);
             writer.Close();
         }
         MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                                       .SetTitle(filename)
                                       .SetMimeType("application/octet-stream")
                                       .Build();
         IDriveFolder driveFolder = null;
         //получаем папку по ID
         driveFolder = driveFolder ?? folderBackUpId.AsDriveFolder();
         //если папка не ноль то создаем файл
         if (driveFolder != null)
         {
             var s = driveFolder.CreateFile(_googleApiClient, changeSet, content.DriveContents);
             CreateAlertDialog("", successMessage);
         }
     }
     catch (Exception er)
     {
         CreateAlertDialog("", errorMessage + er.Message);
     }
 }
Exemplo n.º 2
0
        private void WriteDriveFile(Stream stream, IDriveApiDriveContentsResult result)
        {
            //------ THIS IS AN EXAMPLE FOR PICTURE ------
            //ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
            //image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
            //try {
            //  outputStream.write(bitmapStream.toByteArray());
            //} catch (IOException e1) {
            //  Log.i(TAG, "Unable to write file contents.");
            //}
            //// Create the initial metadata - MIME type and title.
            //// Note that the user will be able to change the title later.
            //MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
            //    .setMimeType("image/jpeg").setTitle("Android Photo.png").build();

            //------ THIS IS AN EXAMPLE FOR FILE --------
            var path     = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var filename = Path.Combine(path, Constants.BackupFileName);

            using (var streamWriter = new StreamWriter(filename, true))
            {
                var json = JsonConvert.SerializeObject(DebtsManager.CurrentDebts);
                streamWriter.WriteLine(json);
            }

            var message = String.Format(Utils.GetStringFromResource(Resource.String.upload), Utils.GetStringFromResource(Resource.String.app_name));

            Utils.ShowToast(message);
            var theFile = new Java.IO.File(filename);             //>>>>>> WHAT FILE ?

            try
            {
                var    fileInputStream = new FileInputStream(theFile);
                byte[] buffer          = new byte[1024];
                int    bytesRead;
                while ((bytesRead = fileInputStream.Read(buffer)) != -1)
                {
                    stream.Write(buffer, 0, bytesRead);
                }
            }
            catch (Java.IO.IOException e1)
            {
                Debug.WriteLine("U AR A MORON! Unable to write file contents.", e1);
            }

            MetadataChangeSet changeSet = new MetadataChangeSet.Builder().SetTitle(theFile.Name).SetMimeType("text/plain").SetStarred(false).Build();
            var folder = _driveId.AsDriveFolder();

            folder.CreateFile(_googleApiClient, changeSet, result.DriveContents)
            .SetResultCallback(this);

            ClearDirectory(path);
        }
Exemplo n.º 3
0
        //получаем файл backup
        private async Task GetBackUpFile(IDriveApiDriveContentsResult contentResults)
        {
            try
            {
                var contentFile = new StringBuilder();
                //получаем папку backup
                DriveId folderBackUpId = FindItems(folderName).Result;
                if (folderBackUpId == null)
                {
                    CreateAlertDialog("", errorMessage);
                    //папка с backup не обнаружена
                }
                else
                {
                    IDriveFolder driveFolder = null;
                    IDriveFile   driveFile   = null;
                    //получаем папку по ID
                    driveFolder = driveFolder ?? folderBackUpId.AsDriveFolder();
                    //если папка не ноль то получаем файлы
                    if (driveFolder != null)
                    {
                        var filesResult = await driveFolder.ListChildrenAsync(_googleApiClient);

                        Java.Util.Date temp = null;
                        foreach (var item in filesResult.MetadataBuffer)
                        {
                            if (item.Title.Contains(filename))
                            {
                                if (temp == null || !temp.After(item.ModifiedDate))
                                {
                                    temp      = item.ModifiedDate;
                                    driveFile = item.DriveId.AsDriveFile();
                                }
                            }
                        }

                        //чтение файла из Google drive и получение строки в BAse64

                        var readFile = await driveFile.OpenAsync(_googleApiClient, DriveFile.ModeReadOnly, null);

                        using (var inpstr = readFile.DriveContents.InputStream)
                            using (var streamReade = new StreamReader(inpstr))
                            {
                                while (streamReade.Peek() >= 0)
                                {
                                    contentFile.Append(await streamReade.ReadLineAsync());
                                }
                            }
                        //конвертируем строку из base64 и записываем в файл БД(переписываем)
                        byte[] bytes = Convert.FromBase64String(contentFile.ToString());
                        System.IO.File.WriteAllBytes(pathToDb, bytes);
                        CreateAlertDialog("", successMessage);
                    }
                }
            }
            catch (Exception er)
            {
                Log.Logger.Error(er.Message, er.StackTrace);
                CreateAlertDialog("", errorMessage);
            }
        }