public PlotViewModel(INavigationService navigationService, IAudiogramPlot audiogramPlot, IStorageFolder storageFolder) : base(navigationService) { this.storageFolder = storageFolder; this.audiogramPlot = audiogramPlot; }
private static async Task DoCreateFromDirectory(IStorageFolder source, Stream destinationArchive, CompressionLevel? compressionLevel, Encoding entryNameEncoding) { // var notCreated = true; var fullName = source.Path; using (var destination = Open(destinationArchive, ZipArchiveMode.Create, entryNameEncoding)) { foreach (var item in await source.GetStorageItemsRecursive()) { // notCreated = false; var length = item.Path.Length - fullName.Length; var entryName = item.Path.Substring(fullName.Length, length).TrimStart('\\', '/'); if (item is IStorageFile) { var entry = await DoCreateEntryFromFile(destination, (IStorageFile)item, entryName, compressionLevel); } else { destination.CreateEntry(entryName + '\\'); } } } }
public ItemRepository(IStorageService storageService) { _storageService = storageService.Local; _storageFolder = ApplicationData.Current.LocalFolder; LoadItems().ConfigureAwait(false); }
public GameRouletteModelLogic(IStorageFolder folder, IStorage storage, IStorageFile file, IImage image) { _folder = folder; _storage = storage; _file = file; _image = image; }
public async Task<Info> GetInfo(IStorageFolder folder) { Info retval = null; bool found = true; StorageFile info = null; try { info = await folder.GetFileAsync("Info.info"); } catch(FileNotFoundException fnf) { found = false; } if (!found) { retval = Info.New(); await SaveInfo(folder, retval); } else { using(var infoStream = await info.OpenReadAsync()) using(Stream stream = infoStream.AsStream()) { XDocument document = XDocument.Load(stream); retval = new Info(document); } } return retval; }
private async Task CreateFileInFolderAsync(IStorageFolder targetFolder, string suggestedFileName) { var newTextFile = await targetFolder.CreateFileAsync(suggestedFileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName); // This is a really useful way to write text to a file. For demo purposes, I will just store a timestamp in a text file. await FileIO.WriteTextAsync(newTextFile, String.Format("File created at: {0}", DateTime.Now.ToString())); LastStatus.Text = String.Format("Created {0}", newTextFile.Path); }
public async Task<string> ReadFile(IStorageFolder folder, string fileName) { var dataFolder = await folder.GetFolderAsync(DATA_FOLDER_PATH); var file = await dataFolder.GetFileAsync(fileName); var content = await FileIO.ReadTextAsync(file); return content; }
public async Task SaveInfo(IStorageFolder folder, Info info) { Stream stream = new MemoryStream(); info.Document.Save(stream); stream.Position = 0; await WriteFile("Info.info", folder, stream); }
private static async Task<IReadOnlyList<StorageFile>> GetFilesInFolderAsync(IStorageFolder folder) { List<StorageFile> output = new List<StorageFile>(); var files = await folder.GetFilesAsync().AsTask().ConfigureAwait(false); output.AddRange(files); var folders = await folder.GetFoldersAsync().AsTask().ConfigureAwait(false); foreach (var item in folders) { output.AddRange(await GetFilesInFolderAsync(item).ConfigureAwait(false)); } return output; }
private ImageResults() { m_lockObject = new object(); m_stopwatch = new Stopwatch(); m_saveTask = KnownFolders.PicturesLibrary.CreateFolderAsync("LumiaImagingExtrasTestResults", CreationCollisionOption.OpenIfExists) .AsTask() .ContinueWith(folderTask => { m_folder = folderTask.Result; }, TaskContinuationOptions.OnlyOnRanToCompletion); }
private IStorageFolder getDirectoryInfo(IStorageFolder parentFolder, CloudStorage cloudStorage) { if (parentFolder == null) parentFolder = new YandexStorageFolder { Files = new List<IStorageFile>(), Name = string.Empty, ParentFolder = null, Path = "/", SubFolders = new List<IStorageFolder>() }; var cloudDirectoryEntry = cloudStorage.GetFolder(parentFolder.Path); if (cloudDirectoryEntry == null || cloudDirectoryEntry.Count == 0) return parentFolder; else { foreach (var dirItem in cloudDirectoryEntry) { if (dirItem.Length == 0) { var subfolder = new YandexStorageFolder { Files = new List<IStorageFile>(), Name = dirItem.Name, ParentFolder = parentFolder, Path = string.Concat(parentFolder.Path, dirItem.Name, "/"), SubFolders = new List<IStorageFolder>(), DateTime = dirItem.Modified }; parentFolder.SubFolders.Add(GetDirectoryInfo(subfolder)); } else parentFolder.Files.Add(new YandexStorageFile { DateTime = dirItem.Modified, Extension = Path.GetExtension(dirItem.Name).ToLower(), Name = dirItem.Name, Size = dirItem.Length, ParentFolder = parentFolder }); } } return parentFolder; }
/// <summary> /// Creates a new <see cref="WinRTFolder"/> /// </summary> /// <param name="wrappedFolder">The WinRT <see cref="IStorageFolder"/> to wrap</param> public WinRTFolder(IStorageFolder wrappedFolder) { _wrappedFolder = wrappedFolder; if (_wrappedFolder.Path == Windows.Storage.ApplicationData.Current.LocalFolder.Path #if !WINDOWS_PHONE || _wrappedFolder.Path == Windows.Storage.ApplicationData.Current.RoamingFolder.Path #endif ) { _isRootFolder = true; } else { _isRootFolder = false; } }
public async Task<bool> ChooseNewFolderAsync() { FolderPicker folderPicker = new FolderPicker() { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; folderPicker.FileTypeFilter.Add(".xml"); IStorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { excuseFolder = folder; return true; } MessageDialog warningDialog = new MessageDialog("No excuse folder chosen"); await warningDialog.ShowAsync(); return false; }
private DirectoryData GetDirectoryData(IStorageFolder folder) { if (folder == null) return null; // TODO find a better way to get the folder's date // var folderEntry = isp.GetFile(folder.GetPath() + '/' + AzureFileSystem.FolderEntry); return new DirectoryData { Name = folder.GetName(), VirtualPath = "/" + folder.GetPath(), Created = DateTime.UtcNow, Updated = DateTime.UtcNow, //Created = folderEntry.GetLastUpdated(), //Updated = folderEntry.GetLastUpdated() }; }
public IStorageFolder GetDirectoryInfo(IStorageFolder parentFolder) { IStorageFolder folder = null; CloudStorage cloudStorage = null; try { cloudStorage = new CloudStorage(); cloudStorage.Open(config, credentials); folder = getDirectoryInfo(parentFolder, cloudStorage); } finally { if (cloudStorage != null && cloudStorage.IsOpened) cloudStorage.Close(); } return folder; }
internal async Task<IPicLibFolder> InternalGetSnapshotAsync(IStorageFolder current) { var fs = await current.GetFilesAsync(); var folders = await Task.WhenAll((await current.GetFoldersAsync()).Select(async x => await InternalGetSnapshotAsync(x))); var filesLast = (await Task.WhenAll(fs.Select(async x => await x.GetBasicPropertiesAsync()))) .Select(x => x.DateModified) .Aggregate(DateTimeOffset.MinValue, (x, y) => x > y ? x : y); var foldersLast = folders.Select(x => DateTimeOffset.Parse(x.LastFileEditTime)) .Aggregate(DateTimeOffset.MinValue, (x, y) => x > y ? x : y); ; var picf = new PicLibFolder() { FileCount = fs.Count, LastFileEditTime = ((filesLast > foldersLast) ? filesLast : foldersLast).ToString(), UriString = current.Path, Folders = folders }; return picf; }
public static Task CreateFromDirectory(IStorageFolder source, Stream destinationArchive) { return DoCreateFromDirectory(source, destinationArchive, new CompressionLevel?(), null); }
async public void readfileFromSandbox(string fileToken) { // enables progress indicator //ProgressIndicator indicator = SystemTray.ProgressIndicator; //if (indicator != null) //{ // //indicator.Text = "载入文件中 ..."; // //indicator.IsVisible = true; //} try { // get file of the specific token // Create or open the routes folder. IStorageFolder routesFolder = ApplicationData.Current.LocalFolder; //// purge all files from the Routes folder. //Debug.WriteLine("deleting all files within folder"); //IEnumerable<StorageFile> files = await routesFolder.GetFilesAsync(); //// Add each GPX file to the Routes collection. //foreach (StorageFile f in files) //{ // await f.DeleteAsync(); //} // Copy the route (.GPX file) to the Routes folder. IStorageFile esf = await routesFolder.GetFileAsync(filepath); if (esf != null) { Debug.WriteLine("found file " + esf.Name); if (esf.Path.EndsWith(".txtx")) { // print its content var fileStream = await esf.OpenReadAsync(); Stream x = fileStream.AsStream(); byte[] buffer = new byte[x.Length]; x.Read(buffer, 0, (int)x.Length); x.Close(); string result = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length); //Debug.WriteLine(result); //this.title.Text = "阅读器"; //Debug.WriteLine("title changed"); //this.content.Text = result.Substring(0, 10000); //Debug.WriteLine("content changed"); this.contentString = result; // cut content into pages this.cutContentIntoPages(); // display first page this.currentPage = 0; this.displayCurrentPage(); } } Debug.WriteLine("done"); } catch (FileNotFoundException) { // No Routes folder is present. this.content.Text = "Error loading file, reason: file not found"; Debug.WriteLine("file not found."); } }
internal Directory(IStorageFolder folder) { this.folder = folder; }
public Windows.Foundation.IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { throw new NotImplementedException(); }
public IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { return null; }
public IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => AsyncAction.FromTask(ct => _impl.Move(ct, destinationFolder, desiredNewName, option));
public IAsyncAction MoveAsync(IStorageFolder destinationFolder) => AsyncAction.FromTask(ct => _impl.Move(ct, destinationFolder, Name, NameCollisionOption.FailIfExists));
public IAsyncOperation <StorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => AsyncOperation <StorageFile> .FromTask((ct, _) => _impl.Copy(ct, destinationFolder, desiredNewName, option));
public IAsyncOperation <StorageFile> CopyAsync(IStorageFolder destinationFolder) => AsyncOperation <StorageFile> .FromTask((ct, _) => _impl.Copy(ct, destinationFolder, global::System.IO.Path.GetFileName(Path), NameCollisionOption.FailIfExists));
public StorageFolderViewModel(IStorageFolder model) : base(model) { Children = new ObservableStorageItemCollection(this); }
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { return(File.MoveAsync(destinationFolder, desiredNewName, option)); }
private static async Task<bool> IsDirEmpty(IStorageFolder possiblyEmptyDir) { return (await possiblyEmptyDir.GetFilesAsync()).Count == 0; }
public IAsyncAction MoveAsync(IStorageFolder destinationFolder) { return null; }
internal Task Move(CancellationToken ct, IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => _impl.Move(ct, destinationFolder, desiredNewName, option);
public IAsyncOperation<StorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) { return null; }
public override IAsyncOperation <BaseStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName) { return(CopyAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists)); }
private static IMediaFolder BuildMediaFolder(IStorageFolder folder) { return new MediaFolder { Name = folder.GetName(), SizeField = new Lazy<long>(folder.GetSize), LastUpdated = folder.GetLastUpdated(), MediaPath = folder.GetPath() }; }
public async Task <IStorageFile> CopyAsync(IStorageFolder destinationFolder) => await CopyAsync(destinationFolder, Name);
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName) { return(File.MoveAsync(destinationFolder, desiredNewName)); }
/// <summary> /// Initializes <see cref="FileToPick"/> with the provided value. /// </summary> /// <param name="pickedFolder"></param> public MockFolderPickerService(IStorageFolder pickedFolder) { FileToPick = pickedFolder; }
public ShaderContentManager(IServiceProvider services, IStorageFolder rootFolder) : base(services, rootFolder) { }
/// <summary> /// No-op. Returns a completed task. /// </summary> /// <param name="folder"></param> /// <param name="fileToSelect"></param> /// <returns></returns> public Task LaunchFolderWithSelectionAsync(IStorageFolder folder, ITestableFile fileToSelect) { FolderLaunched?.Invoke(this, EventArgs.Empty); return(Task.CompletedTask); }
private void UpdateDynamicSystemData() { DynamicSystemData = new DynamicSystemInfo(); try { MEMORYSTATUSEX memoryStatus = new MEMORYSTATUSEX(); GlobalMemoryStatusEx(memoryStatus); DynamicSystemData.PhysicalMemory = $"total = {memoryStatus.ullTotalPhys / GB:N2} GB, available = {memoryStatus.ullAvailPhys / GB:N2} GB"; DynamicSystemData.PhysicalPlusPagefile = $"total = {memoryStatus.ullTotalPageFile / GB:N2} GB, available = {memoryStatus.ullAvailPageFile / GB:N2} GB"; DynamicSystemData.VirtualMemory = $"total = {memoryStatus.ullTotalVirtual / GB:N2} GB, available = {memoryStatus.ullAvailVirtual / GB:N2} GB"; ulong pageFileOnDisk = memoryStatus.ullTotalPageFile - memoryStatus.ullTotalPhys; DynamicSystemData.PagefileOnDisk = $"{pageFileOnDisk / GB:N2} GB"; DynamicSystemData.MemoryLoad = $"{memoryStatus.dwMemoryLoad}%"; } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "MEMORYSTATUSEX", ex.Message); } bool isBatteryAvailable = true; try { SYSTEM_POWER_STATUS powerStatus = new SYSTEM_POWER_STATUS(); GetSystemPowerStatus(ref powerStatus); DynamicSystemData.ACLineStatus = powerStatus.ACLineStatus.ToString(); DynamicSystemData.BatteryChargeStatus = $"{powerStatus.BatteryChargeStatus:G}"; if (powerStatus.BatteryChargeStatus == BatteryFlag.NoSystemBattery || powerStatus.BatteryChargeStatus == BatteryFlag.Unknown) { isBatteryAvailable = false; DynamicSystemData.BatteryLife = "n/a"; } else { DynamicSystemData.BatteryLife = $"{powerStatus.BatteryLifePercent}%"; } DynamicSystemData.BatterySaver = powerStatus.BatterySaver.ToString(); } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "SYSTEM_POWER_STATUS", ex.Message); } if (isBatteryAvailable) { try { Battery battery = Battery.AggregateBattery; BatteryReport batteryReport = battery.GetReport(); DynamicSystemData.ChargeRate = $"{batteryReport.ChargeRateInMilliwatts:N0} mW"; DynamicSystemData.Capacity = $"design = {batteryReport.DesignCapacityInMilliwattHours:N0} mWh, " + $"full = {batteryReport.FullChargeCapacityInMilliwattHours:N0} mWh, " + $"remaining = {batteryReport.RemainingCapacityInMilliwattHours:N0} mWh"; } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "BatteryReport", ex.Message); } } else { DynamicSystemData.ChargeRate = "n/a"; DynamicSystemData.Capacity = "n/a"; } try { ulong freeBytesAvailable; ulong totalNumberOfBytes; ulong totalNumberOfFreeBytes; // You can only specify a folder path that this app can access, but you can // get full disk information from any folder path. IStorageFolder appFolder = ApplicationData.Current.LocalFolder; GetDiskFreeSpaceEx(appFolder.Path, out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes); DynamicSystemData.TotalDiskSize = $"{totalNumberOfBytes / GB:N2} GB"; DynamicSystemData.DiskFreeSpace = $"{freeBytesAvailable / GB:N2} GB"; } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "GetDiskFreeSpaceEx", ex.Message); } try { IntPtr infoPtr = IntPtr.Zero; uint infoLen = (uint)Marshal.SizeOf <FIXED_INFO>(); int ret = -1; while (ret != ERROR_SUCCESS) { infoPtr = Marshal.AllocHGlobal(Convert.ToInt32(infoLen)); ret = GetNetworkParams(infoPtr, ref infoLen); if (ret == ERROR_BUFFER_OVERFLOW) { // Try again with a bigger buffer. Marshal.FreeHGlobal(infoPtr); continue; } } FIXED_INFO info = Marshal.PtrToStructure <FIXED_INFO>(infoPtr); DynamicSystemData.DomainName = info.DomainName; string nodeType = string.Empty; switch (info.NodeType) { case BROADCAST_NODETYPE: nodeType = "Broadcast"; break; case PEER_TO_PEER_NODETYPE: nodeType = "Peer to Peer"; break; case MIXED_NODETYPE: nodeType = "Mixed"; break; case HYBRID_NODETYPE: nodeType = "Hybrid"; break; default: nodeType = $"Unknown ({info.NodeType})"; break; } DynamicSystemData.NodeType = nodeType; } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "GetNetworkParams", ex.Message); } try { ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile(); DynamicSystemData.ConnectedProfile = profile.ProfileName; NetworkAdapter internetAdapter = profile.NetworkAdapter; DynamicSystemData.IanaInterfaceType = $"{(IanaInterfaceType)internetAdapter.IanaInterfaceType}"; DynamicSystemData.InboundSpeed = $"{internetAdapter.InboundMaxBitsPerSecond / MBPS:N0} Mbps"; DynamicSystemData.OutboundSpeed = $"{internetAdapter.OutboundMaxBitsPerSecond / MBPS:N0} Mbps"; IReadOnlyList <HostName> hostNames = NetworkInformation.GetHostNames(); HostName connectedHost = hostNames.Where (h => h.IPInformation != null && h.IPInformation.NetworkAdapter != null && h.IPInformation.NetworkAdapter.NetworkAdapterId == internetAdapter.NetworkAdapterId) .FirstOrDefault(); if (connectedHost != null) { DynamicSystemData.HostAddress = connectedHost.CanonicalName; DynamicSystemData.AddressType = connectedHost.Type.ToString(); } } catch (Exception ex) { App.AnalyticsWriteLine("MainPage.UpdateDynamicSystemData", "GetInternetConnectionProfile", ex.Message); } dynamicDataGrid.DataContext = DynamicSystemData; }
public static async Task Initialize() { _logger = new OutputLogger(typeof(TripPlannerProviderPassthrough)); Log("Initializing TripPlannerProvider."); _accessTokenProvider = new AccessTokenProvider() { Logger = new OutputLogger(nameof(AccessTokenProvider)) }; _accessTokenFolder = ApplicationData.Current.LocalFolder; if (!File.Exists(_accessTokenFolder.Path + "\\CurrentAccessToken.txt") || await IsFileEmpty()) { _accessTokenFile = await _accessTokenFolder.CreateFileAsync("CurrentAccessToken.txt", CreationCollisionOption.ReplaceExisting); Log("Created new access token file.", "Out"); } else { _accessTokenFile = await _accessTokenFolder.GetFileAsync("CurrentAccessToken.txt"); Log("Load access token from file.", "In"); } AccessToken token; Func <Task <AccessToken> > createNewToken = async() => { AccessToken newAccessToken = await _accessTokenProvider.GetAccessTokenAsync(); string serialized = Serialize(newAccessToken); await FileIO.WriteTextAsync(_accessTokenFile, serialized); return(newAccessToken); }; if (await IsFileEmpty()) // File should be empty if the file was just created. { Log("Could not find access token on file."); token = await createNewToken(); } else { var data = await FileIO.ReadLinesAsync(_accessTokenFile); string[] serializedRetrieved = data.ToArray(); AccessToken retrievedAccessToken = Deserialize(serializedRetrieved); if (retrievedAccessToken.ExpiresDateTime < DateTime.Now) { Log("Access token has expired. Requesting new access token."); token = await createNewToken(); } else { token = retrievedAccessToken; } } _tripPlannerProvider = new TripPlannerProvider(token) { Logger = new OutputLogger(nameof(TripPlannerProvider)) }; //_tripPlannerProvider = new TripPlannerProviderMock(); Log($"Access token is valid to {token.ExpiresDateTime}.", "Info"); Log("Initializing complete."); }
private static async Task <StorageFolder> MoveDirectoryAsync(IStorageFolder sourceFolder, IStorageFolder destinationDirectory, string sourceRootName, CreationCollisionOption collision = CreationCollisionOption.FailIfExists) { StorageFolder createdRoot = await destinationDirectory.CreateFolderAsync(sourceRootName, collision); destinationDirectory = createdRoot; foreach (StorageFile fileInSourceDir in await sourceFolder.GetFilesAsync()) { await fileInSourceDir.MoveAsync(destinationDirectory, fileInSourceDir.Name, NameCollisionOption.GenerateUniqueName); } foreach (StorageFolder folderinSourceDir in await sourceFolder.GetFoldersAsync()) { await MoveDirectoryAsync(folderinSourceDir, destinationDirectory, folderinSourceDir.Name); } App.JumpList.RemoveFolder(sourceFolder.Path); return(createdRoot); }
/// <summary> /// Creates a StorageServiceBase instance. /// </summary> /// <param name="rootFolder">The root folder.</param> public StorageServiceBase(IStorageFolder rootFolder) { RootFolder = rootFolder; }
private async static Task <StorageFolder> CloneDirectoryAsync(IStorageFolder sourceFolder, IStorageFolder destinationFolder, string sourceRootName, CreationCollisionOption collision = CreationCollisionOption.FailIfExists) { StorageFolder createdRoot = await destinationFolder.CreateFolderAsync(sourceRootName, collision); destinationFolder = createdRoot; foreach (IStorageFile fileInSourceDir in await sourceFolder.GetFilesAsync()) { await fileInSourceDir.CopyAsync(destinationFolder, fileInSourceDir.Name, NameCollisionOption.GenerateUniqueName); } foreach (IStorageFolder folderinSourceDir in await sourceFolder.GetFoldersAsync()) { await CloneDirectoryAsync(folderinSourceDir, destinationFolder, folderinSourceDir.Name); } return(createdRoot); }
private static MediaFolder BuildMediaFolder(IStorageFolder folder) { return new MediaFolder { Name = folder.GetName(), Size = folder.GetSize(), LastUpdated = folder.GetLastUpdated(), MediaPath = folder.GetPath() }; }
public WindowsStorageDirectory(IStorageFolder storage) { _storage = storage; _path = storage.Path; }
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option) => throw new NotSupportedException();
public IAsyncAction MoveAsync(IStorageFolder destinationFolder, string desiredNewName) { return null; }
public MockGiveXRestClient(IStorageService storageService) { _storageInstalledFolder = storageService.StorageFolder; }
public IAsyncOperation<StorageFile> CopyAsync(IStorageFolder destinationFolder) { return null; }
public MockReasonListRestClient(IStorageService storageService) { _storageInstalledFolder = storageService.StorageFolder; }
public Windows.Foundation.IAsyncOperation<StorageFile> CopyAsync(IStorageFolder destinationFolder) { throw new NotImplementedException(); }
internal static async Task <bool> LaunchFolder(IStorageFolder folder) { return(await Launcher.LaunchFolderAsync(folder)); }
public Windows.Foundation.IAsyncAction MoveAsync(IStorageFolder destinationFolder) { throw new NotImplementedException(); }
public async Task <IStorageFile> CopyAsync(IStorageFolder destinationFolder) { return(await this.CopyAsync(destinationFolder, this.Name, NameCollisionOption.FailIfExists)); }
private async Task WriteFile(string fileName, IStorageFolder folder, Stream data) { try { var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (data) using (var writeStream = await file.OpenStreamForWriteAsync()) { await writeStream.WriteAsync(data.ToArray(), 0, (int)data.Length); await writeStream.FlushAsync(); } } catch(Exception e) { } }
private async void clipHeadOKButton_Click(object sender, RoutedEventArgs e) { upClipHeadProgressBar.Visibility = Visibility.Visible; try { //HttpClient _httpClient = new HttpClient(); //CancellationTokenSource _cts = new CancellationTokenSource(); RenderTargetBitmap mapBitmap = new RenderTargetBitmap(); await mapBitmap.RenderAsync(headScrollViewer); var pixelBuffer = await mapBitmap.GetPixelsAsync(); IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IStorageFile saveFile = await applicationFolder.CreateFileAsync("temphead.png", CreationCollisionOption.OpenIfExists); using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite)) { var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream); encoder.SetPixelData( BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)mapBitmap.PixelWidth, (uint)mapBitmap.PixelHeight, DisplayInformation.GetForCurrentView().LogicalDpi, DisplayInformation.GetForCurrentView().LogicalDpi, pixelBuffer.ToArray()); await encoder.FlushAsync(); } var vault = new Windows.Security.Credentials.PasswordVault(); var credentialList = vault.FindAllByResource(resourceName); credentialList[0].RetrievePassword(); //string uphead = await NetWork.headUpload(appSetting.Values["stuNum"].ToString(), "ms-appdata:///local/temphead.png"); string uphead = await NetWork.headUpload(credentialList[0].UserName, "ms-appdata:///local/temphead.png"); Debug.WriteLine(uphead); if (uphead != "") { JObject obj = JObject.Parse(uphead); if (Int32.Parse(obj["state"].ToString()) == 200) { ClipHeadGrid.Visibility = Visibility.Collapsed; BackOpacityGrid.Visibility = Visibility.Collapsed; initHeadImage(); } else { Utils.Toast("头像上传错误"); } } else { Utils.Toast("头像上传错误"); } upClipHeadProgressBar.Visibility = Visibility.Collapsed; } catch (Exception) { Debug.WriteLine("设置头像,保存新头像异常"); } }
public async Task <IStorageFile> CopyTo(IStorageFolder folderdestination) { return(await CopyTo(folderdestination, Name)); }
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder) { return(File.MoveAsync(destinationFolder)); }
public async Task <IStorageFile> CopyTo(IStorageFolder folderdestination, string filenamewithextension) { return(await CopyTo(folderdestination, filenamewithextension, NameCollisionOption.FailIfExists)); }
public override IAsyncAction MoveAsync(IStorageFolder destinationFolder) => throw new NotSupportedException();