DeleteAsync() 개인적인 메소드

private DeleteAsync ( ) : IAsyncAction
리턴 IAsyncAction
예제 #1
0
        public async Task When_DeleteFile()
        {
            var _folder = Windows.Storage.ApplicationData.Current.LocalFolder;

            Assert.IsNotNull(_folder, "cannot get LocalFolder - error outside tested method");

            Windows.Storage.StorageFile _file = null;

            try
            {
                _file = await _folder.CreateFileAsync(_filename, Windows.Storage.CreationCollisionOption.FailIfExists);

                Assert.IsNotNull(_file, "cannot create file - error outside tested method");
            }
            catch
            {
                Assert.Fail("CreateFile exception - error outside tested method");
            }

            // try delete file
            try
            {
                await _file.DeleteAsync();
            }
            catch
            {
                Assert.Fail("DeleteAsync exception - error in tested method");
            }

            // check if method works
            var _fileAfter = await _folder.TryGetItemAsync("test-deletingfile.txt");

            Assert.IsNull(_fileAfter, "file is not deleted - tested method fails");
        }
예제 #2
0
        //Delete a file
        public async Task DeleteFile()
        {
            Windows.Storage.StorageFile sampleFile =
                await textfileFolder.GetFileAsync(FileName + ".txt");

            await sampleFile.DeleteAsync();
        }
예제 #3
0
        async void TranscodeCancel(object sender, RoutedEventArgs e)
        {
            try
            {
                _cts.Cancel();
                _cts.Dispose();
                _cts = new CancellationTokenSource();

                if (_OutputFile != null)
                {
                    await _OutputFile.DeleteAsync();
                }
            }
            catch (Exception exception)
            {
                TranscodeError(exception.Message);
            }
        }
예제 #4
0
        /// <summary>
        /// Deletes the changelog.
        /// </summary>
        public static async void DeleteChangelog()
        {
            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile file =
                await storageFolder.GetFileAsync("Changelog.txt");

            await file.DeleteAsync(StorageDeleteOption.Default);
        }
예제 #5
0
 private async Task DeleteTempFile(StorageFile f)
 {
     try
     {
         await f.DeleteAsync();
     }
     catch
     {
         // ignore
     }
 }
예제 #6
0
        public async void Create()
        {
            // Create sample file; replace if exists.
            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("Untitled.txt",
                                                                                         Windows.Storage.CreationCollisionOption.ReplaceExisting);

            File = await _FileService.LoadAsync(sampleFile);

            await sampleFile.DeleteAsync(Windows.Storage.StorageDeleteOption.PermanentDelete);
        }
예제 #7
0
 public static async Task<bool> DeleteFileAsync(StorageFile file)
 {
     try
     {
         await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
         return true;
     }
     catch (Exception ex)
     {
         Debug.WriteLine("Failed to delete file: " + ex);
         return false;
     }
 }
 async void TranscodeFailure(TranscodeFailureReason reason)
 {
     try
     {
         if (_OutputFile != null)
         {
             await _OutputFile.DeleteAsync();
         }
     }
     catch (Exception exception)
     {
     }
 }
예제 #9
0
        private async void clearDataStorage(IUICommand command)
        {
            string DataFile = @"Assets\storage.txt";

            Windows.Storage.StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            Windows.Storage.StorageFile   sampleFile    = await storageFolder.GetFileAsync(DataFile);

            // REMOVE FILE
            await sampleFile.DeleteAsync();

            // CREATE NEW FILE
            await storageFolder.CreateFileAsync(DataFile, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            txtData.Text = "Data byla smazána!";
        }
예제 #10
0
        private async void DeleteFile_OnClick(object sender, RoutedEventArgs e)
        {
            if (listBox.SelectedItem == null)
            {
                return;
            }

            ListBoxItem item = (ListBoxItem)listBox.SelectedItem;

            if (item.Tag is Windows.Storage.StorageFile)
            {
                Windows.Storage.StorageFile file = (Windows.Storage.StorageFile)item.Tag;
                await file.DeleteAsync();
            }
            ScanDir(currentFolder);
        }
예제 #11
0
        /// <summary>
        /// Outputs the changes to online db.
        /// </summary>
        /// <returns></returns>
        public static async Task OutputChanges()
        {
            MySqlConnection dbConnection = DbConnection.getConnection();

            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile file =
                await storageFolder.GetFileAsync("Changelog.txt");

            IList <string> data = await FileIO.ReadLinesAsync(file);

            List <string> queries = data.ToList();

            foreach (var queryItem in queries)
            {
                using (dbConnection)
                {
                    try
                    {
                        dbConnection.Open();
                        var query = dbConnection.CreateCommand();
                        query.CommandText = queryItem;
                        query.ExecuteReader();
                        dbConnection.Close();
                    }
                    catch (MySqlException)
                    {
                        break;
                    }
                }
            }

            using (dbConnection)
            {
                try
                {
                    dbConnection.Open();
                    await file.DeleteAsync(StorageDeleteOption.Default);

                    DataAccess.InitializeDatabase();
                    dbConnection.Close();
                }
                catch (Exception)
                {
                }
            }
        }
예제 #12
0
        private async Task <Windows.Storage.StorageFile> ReencodePhotoAsync(Windows.Storage.StorageFile tempStorageFile, Windows.Storage.FileProperties.PhotoOrientation photoRotation)
        {
            Windows.Storage.Streams.IRandomAccessStream inputStream  = null;
            Windows.Storage.Streams.IRandomAccessStream outputStream = null;
            Windows.Storage.StorageFile photoStorage = null;

            try
            {
                String newPhotoFilename = photoId + "_" + photoCount.ToString() + ".jpg";

                inputStream = await tempStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);

                var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(inputStream);

                photoStorage = await currentFolder.CreateFileAsync(newPhotoFilename, Windows.Storage.CreationCollisionOption.GenerateUniqueName);

                outputStream = await photoStorage.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                outputStream.Size = 0;

                var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                var properties = new Windows.Graphics.Imaging.BitmapPropertySet();
                properties.Add("System.Photo.Orientation", new Windows.Graphics.Imaging.BitmapTypedValue(photoRotation, Windows.Foundation.PropertyType.UInt16));

                await encoder.BitmapProperties.SetPropertiesAsync(properties);

                await encoder.FlushAsync();
            }
            finally
            {
                if (inputStream != null)
                {
                    inputStream.Dispose();
                }

                if (outputStream != null)
                {
                    outputStream.Dispose();
                }

                var asyncAction = tempStorageFile.DeleteAsync(Windows.Storage.StorageDeleteOption.PermanentDelete);
            }

            return(photoStorage);
        }
예제 #13
0
 /// <summary>
 /// Tries to delete file n times , each try is postponed by 5 seconds.
 /// </summary>
 /// <param name="nRetries"></param>
 /// <param name="file"></param>
 public static void TryToRemoveFile(int nRetries,StorageFile file)
 {
     Task.Run( async () =>
     {
         try
         {
             await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
         }
         catch (Exception)
         {
             if (nRetries > 0)
             {
                 await Task.Delay(TimeSpan.FromSeconds(5));
                 TryToRemoveFile(nRetries - 1,file);
             }            
         }
     });
 }
예제 #14
0
        public static async Task resetFolders()
        {
            Windows.Storage.StorageFolder localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   firstfile   = await localfolder.GetFileAsync("firsttime");

            await firstfile.DeleteAsync();

            var folders = await localfolder.GetFoldersAsync();

            foreach (Windows.Storage.StorageFolder folder in folders)
            {
                await folder.DeleteAsync();
            }
            Windows.Storage.StorageFolder stor = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("thumbs", Windows.Storage.CreationCollisionOption.FailIfExists);

            Uri uri = new Uri("ms-appx:///Assets/bookImage.jpg");

            Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);

            Windows.Storage.StorageFolder imageFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync("thumbs");

            await file.CopyAsync(imageFolder, "default.jpg");
        }
    public async void Delete(FlipView display)
    {
        try
        {
            collection = new ObservableCollection<Music>();
            display.ItemsSource = Collection;
            file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
            await file.DeleteAsync();
        }
        catch
        {

        }
    }
예제 #16
0
        /// <summary>
        /// Attempts to upload the given file, and will recursively retry until the MaxRetries limit is reached. 
        /// </summary>
        /// <param name="file">The file to upload. Assumes calling method has sole access to the file. Will delete the file after uploading</param>
        /// <param name="tryNumber">The number of the attempt being made. Should always initially be called with a value of 1</param>
        /// <returns></returns>
        private async Task uploadWithRetry(StorageFile file, int tryNumber = 1)
        {
            HttpResponseMessage response = await oneDriveConnector.UploadFileAsync(file, String.Format("{0}/{1}", App.Controller.XmlSettings.OneDriveFolderPath, DateTime.Now.ToString("yyyy_MM_dd")));
            bool success = await parseResponse(response, tryNumber);
            var events = new Dictionary<string, string>();

            if (success)
            {
                numberUploaded++;
                await file.DeleteAsync();
                this.lastUploadTime = DateTime.Now;
            }
            else if (tryNumber <= MaxTries)
            {
                events.Add("Retrying upload", tryNumber.ToString());
                TelemetryHelper.TrackEvent("FailedToUploadPicture - Next Retry Beginning", events);
                await uploadWithRetry(file, ++tryNumber);
            }
            else
            {
                events.Add("Max upload attempts reached", tryNumber.ToString());
                TelemetryHelper.TrackEvent("FailedToUploadPicture - All Retries failed", events);
            }
        }
예제 #17
0
 internal static async Task ExportTimetable(string exportFileName, StorageFile destinationFile)
 {
     try
     {
         var sourceFile = await (await GetTimetableDirectory()).GetFileAsync(exportFileName);
         await sourceFile.CopyAndReplaceAsync(destinationFile);
         return;
     }
     catch  { }
     await destinationFile.DeleteAsync();
     await new MessageDialog(Strings.TimetableIOExportError, Strings.MessageBoxWarningCaption).ShowAsync();
 }
예제 #18
0
 public static async Task<Object> DeserializeFromFileAsync(Type objectType, StorageFile file, bool deleteFile = false)
 {
     if (file == null) return null;
     try
     {
         Object obj;
         AppEventSource.Log.Debug("Suspension: Checking file..." + file.Name);
         // Get the input stream for the file
         using (IInputStream inStream = await file.OpenSequentialReadAsync())
         {
             // Deserialize the Session State
             DataContractSerializer serializer = new DataContractSerializer(objectType);
             obj = serializer.ReadObject(inStream.AsStreamForRead());
         }
         AppEventSource.Log.Debug("Suspension: Object loaded from file. " + objectType.ToString());
         // Delete the file
         if (deleteFile)
         {
             await file.DeleteAsync();
             deleteFile = false;
             AppEventSource.Log.Info("Suspension: File deleted. " + file.Name);
         }
         return obj;
     }
     catch (Exception e)
     {
         AppEventSource.Log.Error("Suspension: Error when deserializing object. Exception: " + e.Message);
         MessageDialog messageDialog = new MessageDialog("Error when deserializing App settings: " + file.Name + "\n" 
             + "The PDF file is not affected.\n " + "Details: \n" + e.Message);
         messageDialog.Commands.Add(new UICommand("Reset Settings", null, 0));
         messageDialog.Commands.Add(new UICommand("Ignore", null, 1));
         IUICommand command = await messageDialog.ShowAsync();
         switch ((int)command.Id)
         {
             case 0:
                 // Delete file
                 deleteFile = true;
                 break;
             default:
                 deleteFile = false;
                 break;
         }
         return null;
     }
     finally
     {
         // Delete the file if error occured
         if (deleteFile)
         {
             await file.DeleteAsync();
             AppEventSource.Log.Info("Suspension: File deleted due to error. " + file.Name);
         }
     }
 }
        private async Task<bool> TryDeleteFileAsync(StorageFile file)
        {
            try
            {
                await file.DeleteAsync();

                return true;
            }
            catch (IsolatedStorageException)
            {
                return false;
            }
        }
예제 #20
0
        public async static Task<bool> SafeFileDelete(StorageFile file)
        {
            if (file == null)
            {
                return false;
            }

            try
            {
                await file.DeleteAsync();
            }
            catch (FileNotFoundException)
            {
                // Ignore
            }
            catch (Exception)
            {
                var tempPath = GetUndeletedFilesDirectory();
                await WriteFile(Path.Combine(tempPath, string.Format("{0}.txt", Guid.NewGuid())), file.Path);
                return false;
            }
            return true;
        }
예제 #21
0
		public static async Task DeleteFileAsync(StorageFile file)
		{
			if (file != null)
				await file.DeleteAsync();
		}
예제 #22
0
        private async Task <bool> WriteBytesToFile(byte[] audio)
        {
            int    ctr      = 0;
            string fileName = "audioData.dat";

            Windows.Storage.StorageFile audioFile = null;

            while (true)     //HACK
            {
                while (true) //HACK
                {
                    try
                    {
                        audioFile = await storageFolder.GetFileAsync(fileName);

                        if (audioFile != null)
                        {
                            await audioFile.DeleteAsync();
                        }

                        break;
                    }
                    catch (Exception e)
                    {
                        if (e.Message.IndexOf("The system cannot find the file specified") == -1)
                        {
                            int ignoreForNow = 1;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                try
                {
                    audioFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                    await FileIO.WriteBytesAsync(audioFile, audio);

                    break;
                }
                catch (Exception e)
                {
                    try  //TODO - Remove inner exception
                    {
                        audioFile = await storageFolder.GetFileAsync(fileName);

                        await audioFile.DeleteAsync();
                    }
                    catch (Exception ex)
                    {
                        int ignoreForNow = 1;
                    }

                    if (ctr > 5)
                    {
                        throw e;
                    }
                    else
                    {
                        ctr++;
                    }
                }
            }

            return(true); //HACK
        }
예제 #23
0
 /// <summary>
 /// This is used to delete the temporary created file
 /// used in the Share charm and other functions.
 /// </summary>
 public async Task deleteUsedFile()
 {
     // Deletes the temporary created file.
     if (imageOriginal.dstPixels != null)
     {
         file = await ApplicationData.Current.LocalFolder.GetFileAsync("temp.jpg");
         await file.DeleteAsync();
     }
 }
예제 #24
0
 private static async Task DeleteSchedule(BusStop stop, StorageFile file, params string[] routes)
 {
     if (routes == null || routes.Length == 0)
     {
         await file.DeleteAsync();
     }
     else
     {
         WeekSchedule baseSchedule = (await LoadSchedule(stop.ID)) ?? new WeekSchedule();
         baseSchedule.RemoveRoutes(routes);
         if (baseSchedule.IsEmpty)
             await DeleteSchedule(stop, file);
         else
             await OverwriteScheduleAsync(baseSchedule, stop);
     }
 }
예제 #25
0
 public async Task DeleteAsync(StorageFile file)
 {
     await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
 }
예제 #26
0
        public async void StartDownload(StorageFile fileDownload)
        {
            try {
                var fs = await fileDownload.OpenAsync(FileAccessMode.ReadWrite);
                Stream stream = await Response.Content.ReadAsStreamAsync();
                IInputStream inputStream = stream.AsInputStream();
                ulong totalBytesRead = 0;
                while (true)
                {
                    if (CancelTask)
                    {
                        await fileDownload.DeleteAsync(StorageDeleteOption.PermanentDelete);
                        break;
                    }
                    // Read from the web.
                    IBuffer buffer = new Windows.Storage.Streams.Buffer(1024);
                    buffer = await inputStream.ReadAsync(
                        buffer,
                        buffer.Capacity,
                        InputStreamOptions.None);

                    if (buffer.Length == 0)
                    {
                        break;
                    }

                    // Report progress.
                    totalBytesRead += buffer.Length;
                    OnDownloadProgress(totalBytesRead, FileSizeMb);
                    // Write to file.
                    await fs.WriteAsync(buffer);
                }

                inputStream.Dispose();
                fs.Dispose();
                OnDownloadComplete();
            }
            catch (Exception ex)
            {
                OnDownloadCancel(ex.Message);
            }
        }
예제 #27
0
        public async void DownloadStart(Uri source,StorageFile destinationFile)
        {

            try {
                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation download = downloader.CreateDownload(source, destinationFile);
                DownloadStarted();
                await download.StartAsync();

                Tracker myTracker = EasyTracker.GetTracker();
                int progress = (int)(100 * (download.Progress.BytesReceived / (double)download.Progress.TotalBytesToReceive));
                if (progress >= 100)
                {
                    myTracker.SendEvent("Downloads", "Download Finished using Share Target", "Download Successfull using Share Target", 1);

                    BasicProperties basic = await download.ResultFile.GetBasicPropertiesAsync();
                    string size;
                    double siz = basic.Size;
                    //     ulong mb = ulong.Parse(1000000);
                    if (siz > 1000000)
                    {
                        double s = siz / 1000000;
                        size = s.ToString() + "MB";
                    }
                    else
                    {
                        double s = siz / 1000;

                        size = s.ToString() + "KB";
                    }

                    DatabaseController.AddDownload(destinationFile.Name, download.ResultFile.Path, download.ResultFile.DateCreated.DateTime.ToString(), size);

                    DowloadFinish(destinationFile);




                }
                else

                {

                    BasicProperties basic = await download.ResultFile.GetBasicPropertiesAsync();

                    double siz = basic.Size;
                    if (siz == 0)
                    {
                        await destinationFile.DeleteAsync();
                        myTracker.SendEvent("Downloads", "Download Failed due to Server Error", null, 3);
                        MessageDialog m = new MessageDialog("Server is down. Try again later", "Fatal Error");
                        await m.ShowAsync();
                    }
                }
            }
            catch(Exception ex)
            {
                
                Debug.WriteLine(ex.ToString());
               
            }
            /*
            var authClient = new LiveAuthClient();
            var authResult = await authClient.LoginAsync(new string[] { "wl.skydrive", "wl.skydrive_update" });
            if (authResult.Session == null)
            {
                throw new InvalidOperationException("You need to sign in and give consent to the app.");
            }

            var liveConnectClient = new LiveConnectClient(authResult.Session);

            string skyDriveFolder = await CreateDirectoryAsync(liveConnectClient, "PDF Me - Saved PDFs", "me/skydrive");
        */
        }
예제 #28
0
        public static async Task <Windows.Storage.StorageFolder> extractFiles(Windows.Storage.StorageFile zipfilename)
        {
            Windows.Storage.StorageFolder storfolder = null;
            try
            {
                // Create stream for compressed files in memory
                using (MemoryStream zipMemoryStream = new MemoryStream())
                {
                    using (Windows.Storage.Streams.IRandomAccessStream zipStream = await zipfilename.OpenAsync(Windows.Storage.FileAccessMode.Read))
                    {
                        // Read compressed data from file to memory stream
                        using (Stream instream = zipStream.AsStreamForRead())
                        {
                            byte[] buffer = new byte[1024];
                            while (instream.Read(buffer, 0, buffer.Length) > 0)
                            {
                                zipMemoryStream.Write(buffer, 0, buffer.Length);
                            }
                        }
                    }
                    storfolder = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync(zipfilename.DisplayName, Windows.Storage.CreationCollisionOption.GenerateUniqueName);

                    // Create zip archive to access compressed files in memory stream
                    using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Read))
                    {
                        // For each compressed file...
                        foreach (ZipArchiveEntry entry in zipArchive.Entries)
                        {
                            // ... read its uncompressed contents
                            using (Stream entryStream = entry.Open())
                            {
                                if (entry.Name != "")
                                {
                                    string fileName = entry.FullName.Replace("/", @"\");
                                    byte[] buffer   = new byte[entry.Length];
                                    entryStream.Read(buffer, 0, buffer.Length);

                                    // Create a file to store the contents
                                    Windows.Storage.StorageFile uncompressedFile = await storfolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                                    // Store the contents
                                    using (Windows.Storage.Streams.IRandomAccessStream uncompressedFileStream = await uncompressedFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                                    {
                                        using (Stream outstream = uncompressedFileStream.AsStreamForWrite())
                                        {
                                            outstream.Write(buffer, 0, buffer.Length);
                                            outstream.Flush();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                if (storfolder != null)
                {
                    await storfolder.DeleteAsync();
                }
                return(null);
            }
            finally
            {
                zipfilename.DeleteAsync();
            }
            return(storfolder);
        }