/// <summary> /// Moves a file. /// </summary> /// <param name="newPath">The new full path of the file.</param> /// <param name="toFolder">Folder to move to</param> /// <param name="collisionOption">How to deal with collisions with existing files.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A task which will complete after the file is moved. /// </returns> public async Task MoveAsync(string newPath, IFolder toFolder, NameCollisionOption collisionOption, CancellationToken cancellationToken) { Requires.NotNullOrEmpty(newPath, "newPath"); await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); string newDirectory = System.IO.Path.GetDirectoryName(newPath); string newName = System.IO.Path.GetFileName(newPath); for (int counter = 1; ; counter++) { cancellationToken.ThrowIfCancellationRequested(); string candidateName = newName; if (counter > 1) { candidateName = String.Format( CultureInfo.InvariantCulture, "{0} ({1}){2}", System.IO.Path.GetFileNameWithoutExtension(newName), counter, System.IO.Path.GetExtension(newName)); } string candidatePath = PortablePath.Combine(newDirectory, candidateName); if (File.Exists(candidatePath)) { switch (collisionOption) { case NameCollisionOption.FailIfExists: throw new IOException("File already exists."); case NameCollisionOption.GenerateUniqueName: continue; // try again with a new name. case NameCollisionOption.ReplaceExisting: File.Delete(candidatePath); break; } } File.Move(_path, candidatePath); _path = candidatePath; _name = candidateName; return; } }
/// <summary> /// Opens the file /// </summary> /// <param name="fileAccess">Specifies whether the file should be opened in read-only or read/write mode</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A <see cref="Stream"/> which can be used to read from or write to the file</returns> public async Task <Stream> OpenAsync(FileAccess fileAccess, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); if (fileAccess == FileAccess.Read) { return(await File.OpenStreamForReadAsync()); } else if (fileAccess == FileAccess.ReadAndWrite) { return(await File.OpenStreamForWriteAsync()); } else { throw new ArgumentException("Unrecognized FileAccess value: " + fileAccess); } }
/// <inheritdoc /> public async Task <Stream> OpenAsync(FileAccess fileAccess, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); if (fileAccess == FileAccess.Read) { return(File.OpenRead(Path)); } else if (fileAccess == FileAccess.ReadAndWrite) { return(File.Open(Path, FileMode.Open, System.IO.FileAccess.ReadWrite)); } else { throw new ArgumentException($"Unrecognized FileAccess value: {fileAccess}"); } }
public void SwitchOffMainThreadAsync_CanceledMidSwitch() { var cts = new CancellationTokenSource(); var awaitable = AwaitExtensions.SwitchOffMainThreadAsync(cts.Token); var awaiter = awaitable.GetAwaiter(); cts.Cancel(); try { awaiter.GetResult(); Assert.Fail("Expected OperationCanceledException not thrown."); } catch (OperationCanceledException ex) { Assert.AreEqual(cts.Token, ex.CancellationToken); } }
/// <inheritdoc /> public async Task CopyAsync(string newPath, NameCollisionOption collisionOption, CancellationToken cancellationToken) { Requires.NotNullOrEmpty(newPath, "newPath"); await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); var newDirectory = System.IO.Path.GetDirectoryName(newPath); var newName = System.IO.Path.GetFileName(newPath); for (var counter = 1; ; counter++) { cancellationToken.ThrowIfCancellationRequested(); var candidateName = newName; if (counter > 1) { candidateName = $"{System.IO.Path.GetFileNameWithoutExtension(newName)} ({counter}){System.IO.Path.GetExtension(newName)}"; } var candidatePath = System.IO.Path.Combine(newDirectory, candidateName); if (File.Exists(candidatePath)) { switch (collisionOption) { case NameCollisionOption.FailIfExists: throw new IOException("File already exists."); case NameCollisionOption.GenerateUniqueName: continue; // try again with a new name. case NameCollisionOption.ReplaceExisting: File.Delete(candidatePath); break; } } File.Copy(Path, candidatePath); Path = candidatePath; Name = candidateName; return; } }
/// <inheritdoc /> public async Task <ExistenceCheckResult> CheckExistsAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNullOrEmpty(name, "name"); await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); var checkPath = System.IO.Path.Combine(Path, name); if (File.Exists(checkPath)) { return(ExistenceCheckResult.FileExists); } else if (Directory.Exists(checkPath)) { return(ExistenceCheckResult.FolderExists); } else { return(ExistenceCheckResult.NotFound); } }
public async Task WaitForExitAsync_Canceled() { string processName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "/bin/bash"; Process p = Process.Start(new ProcessStartInfo(processName) { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }) !; try { var cts = new CancellationTokenSource(); Task <int> t = AwaitExtensions.WaitForExitAsync(p, cts.Token); Assert.False(t.IsCompleted); cts.Cancel(); await Assert.ThrowsAsync <TaskCanceledException>(() => t); } finally { p.Kill(); } }
public async Task CreateDirectoryAsync(FileSystemPath path, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); if (!path.IsDirectory) { throw new ArgumentException("The specified path is no directory.", "path"); } LinkedList <FileSystemPath> subentities; if (_directories.ContainsKey(path)) { throw new ArgumentException("The specified directory-path already exists.", "path"); } if (!_directories.TryGetValue(path.ParentPath, out subentities)) { throw new DirectoryNotFoundException(); } subentities.AddLast(path); _directories[path] = new LinkedList <FileSystemPath>(); }
public async Task <Stream> OpenAsync(FileAccessOption accessOption, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); switch (accessOption) { case FileAccessOption.ReadOnly: { // Make sure the source file exists EnsureExists(); return(File.OpenRead(Path)); } case FileAccessOption.ReadWrite: return(File.Open(Path, FileMode.OpenOrCreate, FileAccess.ReadWrite)); default: throw new ArgumentOutOfRangeException("accessOption", accessOption, null); } }
public async Task SwitchOffMainThreadAsync_OnMainThread() { // Make this thread look like the main thread by // setting up a synchronization context. var dispatcher = new SynchronizationContext(); var original = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext(dispatcher); try { Thread originalThread = Thread.CurrentThread; await AwaitExtensions.SwitchOffMainThreadAsync(CancellationToken.None); Assert.AreNotSame(originalThread, Thread.CurrentThread); Assert.IsNull(SynchronizationContext.Current); } finally { SynchronizationContext.SetSynchronizationContext(original); } }
public static async Task <ReadOnlyCollection <IListBlobItem> > ListBlobsSegmentedAsync( this CloudBlobContainer container, string prefix, bool useFlatBlobListing, int pageSize, BlobListingDetails details, BlobRequestOptions options, OperationContext operationContext, IProgress <IEnumerable <IListBlobItem> > progress = null, CancellationToken cancellationToken = default(CancellationToken)) { options = options ?? new BlobRequestOptions(); var results = new List <IListBlobItem>(); BlobContinuationToken continuation = null; BlobResultSegment segment; do { Task <string> t = null; t.GetAwaiter(); await t; AwaitExtensions.GetAwaiter(t); segment = await Task.Factory.FromAsync( (cb, state) => container.BeginListBlobsSegmented(prefix, useFlatBlobListing, details, pageSize, continuation, options, operationContext, cb, state).WithCancellation(cancellationToken), ar => container.EndListBlobsSegmented(ar), null); if (progress != null) { progress.Report(segment.Results); } results.AddRange(segment.Results); continuation = segment.ContinuationToken; } while (continuation != null); return(new ReadOnlyCollection <IListBlobItem>(results)); }
public async Task <IFile> CopyAsync(string newPath, CollisionOption collisionOption = CollisionOption.ReplaceExisting, CancellationToken cancellationToken = new CancellationToken()) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); await EnsureExistsAsync(cancellationToken); StorageFile newFile; using (Stream source = await _storageFile.OpenStreamForReadAsync()) { newFile = await StorageFile.GetFileFromPathAsync(newPath) .AsTask(cancellationToken) .ConfigureAwait(false); const int bufferSize = 4096; using (Stream destination = await newFile.OpenStreamForWriteAsync()) { await source.CopyToAsync(destination, bufferSize, cancellationToken); } } return(new WindowsStorageFile(newFile)); }
public async Task <IFile> CopyAsync(string newPath, CollisionOption collisionOption = CollisionOption.ReplaceExisting, CancellationToken cancellationToken = default(CancellationToken)) { // Make sure the source file exists EnsureExists(); await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); using (Stream source = File.Open(_path, FileMode.Open)) { const int bufferSize = 4096; #if __UNIFIED__ || _ANDROID_ using (Stream destination = File.Create(newPath, bufferSize)) #else using (Stream destination = File.Create(newPath, bufferSize, FileOptions.Asynchronous)) #endif { await source.CopyToAsync(destination, bufferSize, cancellationToken); } } return(new DotNetFile(newPath)); }
public async Task <IFile> MoveAsync(string newPath, CollisionOption collisionOption = CollisionOption.ReplaceExisting, CancellationToken cancellationToken = default(CancellationToken)) { // Make sure the source file exists EnsureExists(); await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); string newDirectory = System.IO.Path.GetDirectoryName(newPath); string newName = System.IO.Path.GetFileName(newPath); for (int counter = 1;; counter++) { cancellationToken.ThrowIfCancellationRequested(); string candidateName = newName; if (counter > 1) { candidateName = string.Format( CultureInfo.InvariantCulture, "{0} ({1}){2}", System.IO.Path.GetFileNameWithoutExtension(newName), counter, System.IO.Path.GetExtension(newName)); } string candidatePath = System.IO.Path.Combine(newDirectory, candidateName); if (File.Exists(candidatePath)) { switch (collisionOption) { case CollisionOption.FailIfExists: { throw new UnifiedIOException("File already exists."); } case CollisionOption.GenerateUniqueName: { // Continue with the loop and generate a new name continue; } case CollisionOption.ReplaceExisting: { File.Delete(candidatePath); break; } default: { throw new ArgumentOutOfRangeException("collisionOption", collisionOption, null); } } } File.Move(_path, candidatePath); _path = candidatePath; return(this); } }
public async Task CreateDirectoryAsync(FileSystemPath path, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); CreateDirectory(path); }
public async Task WaitForExit_NullArgument() { await Assert.ThrowsAsync <ArgumentNullException>(() => AwaitExtensions.WaitForExitAsync(null)); }
/// <summary> /// Gets a folder, given its path. /// </summary> /// <param name="path">The path to a directory, as returned from the <see cref="IDirectory.Path"/> property.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A folder for the specified path.</returns> public async Task <IDirectory> GetDirectoryFromPathAsync(string path, CancellationToken cancellationToken = new CancellationToken()) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); return(new DotNetDirectory(path)); }
/// <summary> /// Gets a file, given its path. /// </summary> /// <param name="path">The path to a file, as returned from the <see cref="IFile.Path"/> property.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A file for the given path.</returns> public async Task <IFile> GetFileFromPathAsync(string path, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); return(new DotNetFile(path)); }
public async Task DeleteAsync(FileSystemPath path, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); Delete(path); }
public async Task <bool> ExistsAsync(CancellationToken cancellationToken = default(CancellationToken)) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); return(Directory.Exists(Path)); }
public async Task <bool> ExistsAsync(CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); return(File.Exists(_path)); }
/// <summary> /// Deletes the file /// </summary> /// <returns>A task which will complete after the file is deleted.</returns> public async Task DeleteAsync(CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); await File.DeleteAsync(); }
public async Task <bool> ExistsAsync(FileSystemPath path, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); return(Exists(path)); }
public async Task <Stream> CreateFileAsync(FileSystemPath path, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); return(CreateFile(path)); }
public async Task DeleteAsync(CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); Directory.Delete(_path, true); }
public void when_scheduler_is_null_then_throws() { Assert.Throws <ArgumentNullException> (() => AwaitExtensions.GetAwaiter(null)); }