public async Task <Windows.Networking.BackgroundTransfer.UploadOperation> UploadBackgroundAsync(Windows.Storage.StorageFile sourceFile, string containerName, string blobName, Action <Windows.Networking.BackgroundTransfer.UploadOperation> progressCallback = null) { var properties = await sourceFile.GetBasicPropertiesAsync(); if (properties.Size > (1024 * 1024 * 64)) { throw new Exception("File cannot be larger than 64MB"); } var permissions = Microsoft.WindowsAzure.Storage.Blob.SharedAccessBlobPermissions.Write; var container = this.Parent.GetContainer(containerName); var signature = this.GetSas(permissions, TimeSpan.FromMinutes(5), container.Name, blobName); var uploader = new Windows.Networking.BackgroundTransfer.BackgroundUploader { TransferGroup = Windows.Networking.BackgroundTransfer.BackgroundTransferGroup.CreateGroup(_groupName) }; uploader.SetRequestHeader("Filename", sourceFile.Name); var upload = uploader.CreateUpload(signature, sourceFile); if (progressCallback == null) { return(await upload.StartAsync()); } else { return(await upload.StartAsync().AsTask(new Progress <Windows.Networking.BackgroundTransfer.UploadOperation>(progressCallback))); } }
public async Task <CloudFile> UploadFileAsync(Windows.Storage.StorageFile file) { try { var fileSize = (await file.GetBasicPropertiesAsync()).Size; if (fileSize == 0) { var uploadedFile = await CreateEmptyFileAsync(file.Name); MyLogger.Log($"File upload succeeded!\r\nName: {uploadedFile.Name}\r\nParent: {this.FullName}\r\nID: {uploadedFile.Id}\r\nSize: {fileSize} bytes"); MyLogger.Assert(uploadedFile.Name == file.Name); return(uploadedFile); } MyLogger.Assert(this.IsFolder); var uploader = new Uploaders.FileUploader(this, file, file.Name); indexRetry :; await uploader.StartAsync(); switch (uploader.Status) { case Networker.NetworkStatus.Completed: { MyLogger.Log($"File upload succeeded!\r\nName: {file.Name}\r\nParent: {this.FullName}\r\nID: {uploader.UploadedCloudFile.Id}\r\nSize: {fileSize} bytes"); var ans = new CloudFile(uploader.UploadedCloudFile.Id, file.Name, false, this); return(ans); } case Networker.NetworkStatus.Paused: { MyLogger.Log("Upload paused"); return(null); } default: { if (await MyLogger.Ask("Upload failed, try again?")) { await uploader.StartAsync(); goto indexRetry; } else { MyLogger.Log("Upload canceled"); return(null); } } } } catch (Exception error) { MyLogger.Log(error.ToString()); await MyLogger.Alert(error.ToString()); return(null); } }
/// <summary> /// Gets the basic properties of the current file. /// </summary> /// <returns></returns> public Task <BasicProperties> GetBasicPropertiesAsync() { #if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE return(Task.Run <BasicProperties>(async() => { return await _file.GetBasicPropertiesAsync(); })); #elif __ANDROID__ || __UNIFIED__ || WIN32 || TIZEN return(Task.FromResult <BasicProperties>(new BasicProperties(this))); #else throw new PlatformNotSupportedException(); #endif }
public async Task UploadAsync(Windows.Storage.StorageFile sourceFile, string containerName, string blobName) { var properties = await sourceFile.GetBasicPropertiesAsync(); if (properties.Size > (1024 * 1024 * 64)) { throw new Exception("File cannot be larger than 64MB"); } var container = this.Parent.GetContainer(containerName); var blob = container.GetBlockBlobReference(blobName); await blob.UploadFromFileAsync(sourceFile); }
/// <summary> /// reads the data from the specified file with the offset as the starting point the size /// and writes them to a byte[] buffer /// </summary> /// <param name="fullPath"></param> /// <returns></returns> public async Task <byte[]> Restore(string fullPath, ulong offset, ulong size) { byte[] dataArray = null; try { Windows.Storage.StorageFile file = await applicationData.LocalFolder.GetFileAsync(fullPath); if (file != null) { if (size <= 0) { var prop = await file.GetBasicPropertiesAsync(); if (prop != null) { size = prop.Size; } } var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); if (stream != null) { using (var inputStream = stream.GetInputStreamAt(offset)) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(inputStream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)size); dataArray = new byte[numBytesLoaded]; if (dataArray != null) { dataReader.ReadBytes(dataArray); } } } } } } catch (Exception) { } return(dataArray); }
private async void SetMediaFile(Windows.Storage.StorageFile mediaFile) { const string fileDurationProperty = "System.Media.Duration"; if (mediaFile.ContentType.Contains("video")) { sIsVideoFile = true; } else if (mediaFile.ContentType.Contains("audio")) { sIsVideoFile = false; } else { return; } var stream = await mediaFile.OpenAsync(Windows.Storage.FileAccessMode.Read); mediaElement.SetSource(stream, mediaFile.ContentType); // Get file's basic properties. var propertyNames = new List <string>(); propertyNames.Add(fileDurationProperty); Windows.Storage.FileProperties.BasicProperties basicProperties = await mediaFile.GetBasicPropertiesAsync(); IDictionary <string, object> extraProperties = await mediaFile.Properties.RetrievePropertiesAsync(propertyNames); UInt64 durationTime = (UInt64)extraProperties[fileDurationProperty]; durationTime = durationTime / 10000;/*msに変換*/ TB_MaxTime.Text = GetTimeSpanStr(durationTime); BT_Resume.IsEnabled = true; BT_Stop.IsEnabled = true; SL_Time.IsEnabled = true; SL_Time.Maximum = durationTime; TB_MediaPath.Text = mediaFile.Path.ToString(); }
public async Task When_DateCreated() { var folderForTestFile = Windows.Storage.ApplicationData.Current.LocalFolder; Assert.IsNotNull(folderForTestFile, "cannot get LocalFolder - error outside tested method"); Windows.Storage.StorageFile testFile = null; DateTimeOffset dateBeforeCreating = DateTimeOffset.Now; try { testFile = await folderForTestFile.CreateFileAsync(_filename, Windows.Storage.CreationCollisionOption.FailIfExists); Assert.IsNotNull(testFile, "cannot create file - error outside tested method"); } catch (Exception e) { Assert.Fail($"CreateFile exception - error outside tested method ({e})"); } DateTimeOffset dateAfterCreating = DateTimeOffset.Now; // tests of DateCreated DateTimeOffset dateOnCreating = DateTimeOffset.Now; // unneeded initialization - just to skip compiler error of using uninitialized variable try { dateOnCreating = testFile.DateCreated; } catch (Exception e) { Assert.Fail($"DateCreated exception - error in tested method ({e})"); } // while testing date, we should remember about filesystem date resolution. // FAT: 2 seconds, but we don't have FAT // NTFS: 100 ns // VFAT (SD cards): can be as small as 10 ms // ext4 (internal Android): can be below 1 ms // APFS (since iOS 10.3): 1 ns // HFS+ (before iOS 10.3): 1 s // first, date should not be year 1601 or something like that... if (dateOnCreating < dateBeforeCreating.AddSeconds(-2)) { Assert.Fail("DateCreated: too early - method doesnt work"); } // second, date should not be in future if (dateOnCreating > dateAfterCreating.AddSeconds(2)) { Assert.Fail("DateCreated: too late - method doesnt work"); } // third, it should not be "datetime.now" var initialTimeDiff = DateTimeOffset.Now - dateOnCreating; int loopGuard; for (loopGuard = 20; loopGuard > 0; loopGuard--) // wait for date change for max 5 seconds { await Task.Delay(250); dateOnCreating = testFile.DateCreated; if (DateTimeOffset.Now - dateOnCreating > initialTimeDiff) { break; } } if (loopGuard < 1) { Assert.Fail("DateCreated: probably == DateTime.Now, - method doesnt work"); } // now, test Date Modified DateTimeOffset dateBeforeModify = DateTimeOffset.Now; // modify file Stream fileStream = await testFile.OpenStreamForWriteAsync(); fileStream.Seek(0, SeekOrigin.End); StreamWriter streamWriter = new StreamWriter(fileStream); streamWriter.Write(_filename); // anything - just write String streamWriter.Dispose(); fileStream.Dispose(); DateTimeOffset dateAfterModify = DateTimeOffset.Now; // get DateModified DateTimeOffset dateModified = DateTimeOffset.Now; // unneeded initialization - just to skip compiler error of using uninitialized variable try { dateModified = (await testFile.GetBasicPropertiesAsync()).DateModified; } catch (Exception e) { Assert.Fail($"DateModified exception - error in tested method ({e})"); } // first, date should not be year 1601 or something like that... if (dateModified < dateBeforeModify.AddSeconds(-2)) { Assert.Fail("DateModified: too early - method doesnt work"); } // second, date should not be in future if (dateModified > dateAfterModify.AddSeconds(2)) { Assert.Fail("DateCreated: too late - method doesnt work"); } // third, it should not be "datetime.now" initialTimeDiff = DateTimeOffset.Now - dateModified; for (loopGuard = 20; loopGuard > 0; loopGuard--) // wait for date change for max 5 seconds { await Task.Delay(250); var dateModifiedLoop = (await testFile.GetBasicPropertiesAsync()).DateModified; if (DateTimeOffset.Now - dateModifiedLoop > initialTimeDiff) { break; } } if (loopGuard < 1) { Assert.Fail("DateModified: probably == DateTime.Now, - method doesnt work"); } // last test if (dateModified < dateOnCreating) { Assert.Fail("DateModified == DateCreated, - method doesnt work"); } }
protected async static Task <Windows.Storage.FileProperties.BasicProperties> GetFileBasicPropertiesAsync(Windows.Storage.StorageFile fle) { return(await fle.GetBasicPropertiesAsync()); }
public async Task DownloadFileOnWindowsAsync(Windows.Storage.StorageFile file) { try { MyLogger.Assert(!this.IsFolder); MyLogger.Assert(this.Name == file.Name); var downloader = new CloudFile.Downloaders.FileDownloader(this, file); downloader.MessageAppended += new MessageAppendedEventHandler((msg) => { MyLogger.Log(msg); }); downloader.StatusChanged += new Networker.NetworkStatusChangedEventHandler(async() => { if (downloader.Status == Networker.NetworkStatus.Completed) { MyLogger.Log($"File download succeeded!\r\nName: {file.Name}\r\nPath: {file.Path}\r\nID: {this.Id}\r\nSize: {(await file.GetBasicPropertiesAsync()).Size} bytes"); } }); await downloader.StartAsync(); } catch (Exception error) { MyLogger.Log(error.ToString()); await MyLogger.Alert(error.ToString()); } }
private async void AppBarButton_Click(object sender, RoutedEventArgs e) { Ring.IsActive = true; try { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; // picker.FileTypeFilter.Add(".bin"); // picker.FileTypeFilter.Add(".txt"); picker.FileTypeFilter.Add("*"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { var buffer = await Windows.Storage.FileIO.ReadBufferAsync(file); byte[] bb = buffer.ToArray(); Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync(); // ViewModel.newVid(); int icol = 0; if (ViewModel.ColTabs.Count > 0) { if (ViewModel.ColTabs[0].Name == "New File") { try { VidDoc vidDoc = new VidDoc() { Name = file.DisplayName, Sppan = true, ccc = cout, IsShow = Visibility.Visible, IsShow1 = Visibility.Visible, Poz = 0, Path = file.Path, Size = basicProperties.Size.ToString(), NameType = file.FileType // BiteFile=bb }; ViewModel.ColTabs.Add(vidDoc); // cout++; ViewModel.ColTabs.RemoveAt(0); Tabs.SelectedIndex = 0; vidDoc.bb1 = bb; await vidDoc.OpenF(); //Tabs.SelectedIndex = 0; cout++; } catch (Exception ex) { MessageDialog messageDialog = new MessageDialog(ex.ToString()); await messageDialog.ShowAsync(); } } else { icol = Tabs.SelectedIndex; ViewModel.ColTabs.RemoveAt(icol); VidDoc vidDoc = new VidDoc() { //uuu //jjj Name = file.DisplayName, Sppan = true, ccc = cout, IsShow = Visibility.Visible, IsShow1 = Visibility.Visible, Poz = 0, Path = file.Path, Size = basicProperties.Size.ToString(), NameType = file.FileType // bb1 = bb // BiteFile=bb }; ViewModel.ColTabs.Insert(icol, vidDoc); Tabs.SelectedIndex = icol; vidDoc.bb1 = bb; await vidDoc.OpenF(); cout++; } } else { VidDoc vidDoc = new VidDoc() { //uuu //jjj Name = file.DisplayName, Sppan = true, ccc = cout, IsShow = Visibility.Visible, IsShow1 = Visibility.Visible, Poz = 0, Path = file.Path, Size = basicProperties.Size.ToString(), NameType = file.FileType // bb1 = bb // BiteFile=bb }; ViewModel.ColTabs.Add(vidDoc); cout++; Tabs.SelectedIndex = ViewModel.ColTabs.Count - 1; vidDoc.bb1 = bb; await vidDoc.OpenF(); } Ring.IsActive = false; } else { Ring.IsActive = false; MessageDialog f = new MessageDialog("Файл не открыт"); await f.ShowAsync(); } } catch { Ring.IsActive = false; MessageDialog f = new MessageDialog("Произошла ошибка, возможно файл поврежден"); await f.ShowAsync(); } Ring.IsActive = false; }
private async void OpenNewFile(object sender, RoutedEventArgs e) { // ViewModel.IsShowBar = Visibility.Visible; Ring.IsActive = true; try { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; // picker.FileTypeFilter.Add(".bin"); // picker.FileTypeFilter.Add(".txt"); // picker.FileTypeFilter.Add(".doc"); picker.FileTypeFilter.Add("*"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { var buffer = await Windows.Storage.FileIO.ReadBufferAsync(file); byte[] bb = buffer.ToArray(); Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync(); VidDoc vidDoc = new VidDoc() { //uuu //jjj Name = file.DisplayName, Sppan = true, ccc = cout, IsShow = Visibility.Visible, IsShow1 = Visibility.Visible, Poz = 0, Path = file.Path, Size = basicProperties.Size.ToString(), NameType = file.FileType // bb1 = bb // BiteFile=bb }; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ViewModel.ColTabs.Add(vidDoc ); }); if (ViewModel.ColTabs[0].Name == "New File") { ViewModel.ColTabs.RemoveAt(0); } cout++; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Tabs.SelectedIndex = ViewModel.ColTabs.Count - 1; }); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { vidDoc.bb1 = bb; }); await vidDoc.OpenF(); await OpenF(bb, vidDoc); //ViewModel.IsShowBar = Visibility.Collapsed; Ring.IsActive = false; } else { MessageDialog f = new MessageDialog("Файл не открыт"); await f.ShowAsync(); Ring.IsActive = false; } } catch { MessageDialog f = new MessageDialog("Произошла ошибка, возможно файл поврежден"); await f.ShowAsync(); Ring.IsActive = false; } Ring.IsActive = false; }
private async void Button_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { this.DataContext = file; // this.txtName.Text = file.Name; this.txtPathName.Text = file.Path; this.txtDate.Text = file.DateCreated.ToString(); this.txtType.Text = file.DisplayType; Windows.Storage.FileProperties.BasicProperties basicProperties = await file.GetBasicPropertiesAsync(); this.txtSize.Text = string.Format("{0:n0}", basicProperties.Size) + " bytes"; using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.DecodePixelWidth = 300; await bitmapImage.SetSourceAsync(fileStream); imgDisplay.Source = bitmapImage; } } }