/// <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;
            }
        }
Пример #2
0
        /// <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);
            }
        }
Пример #3
0
        /// <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);
            }
        }
Пример #5
0
        /// <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();
        }
    }
Пример #8
0
        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>();
        }
Пример #9
0
        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));
        }
Пример #12
0
        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));
        }
Пример #13
0
        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));
        }
Пример #14
0
        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);
            }
        }
Пример #15
0
        public async Task CreateDirectoryAsync(FileSystemPath path, CancellationToken cancellationToken)
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            CreateDirectory(path);
        }
Пример #16
0
 public async Task WaitForExit_NullArgument()
 {
     await Assert.ThrowsAsync <ArgumentNullException>(() => AwaitExtensions.WaitForExitAsync(null));
 }
Пример #17
0
        /// <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));
        }
Пример #18
0
        /// <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));
        }
Пример #19
0
        public async Task DeleteAsync(FileSystemPath path, CancellationToken cancellationToken)
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            Delete(path);
        }
Пример #20
0
        public async Task <bool> ExistsAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            return(Directory.Exists(Path));
        }
Пример #21
0
        public async Task <bool> ExistsAsync(CancellationToken cancellationToken)
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            return(File.Exists(_path));
        }
Пример #22
0
        /// <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();
        }
Пример #23
0
        public async Task <bool> ExistsAsync(FileSystemPath path, CancellationToken cancellationToken)
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            return(Exists(path));
        }
Пример #24
0
        public async Task <Stream> CreateFileAsync(FileSystemPath path, CancellationToken cancellationToken)
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            return(CreateFile(path));
        }
Пример #25
0
        public async Task DeleteAsync(CancellationToken cancellationToken)
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            Directory.Delete(_path, true);
        }
Пример #26
0
 public void when_scheduler_is_null_then_throws()
 {
     Assert.Throws <ArgumentNullException> (() => AwaitExtensions.GetAwaiter(null));
 }