/// <summary>
        /// Moves a file.
        /// </summary>
        /// <param name="newPath">The new full path of the file.</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, 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>
        /// Gets a subfolder in this folder
        /// </summary>
        /// <param name="name">The name of the folder to get</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The requested folder, or null if it does not exist</returns>
        public async Task <IFolder> GetFolderAsync(string name, CancellationToken cancellationToken)
        {
            Requires.NotNullOrEmpty(name, "name");
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            EnsureExists();

            string path = System.IO.Path.Combine(Path, name);

            if (!Root.DirectoryExists(path))
            {
                throw new PCLStorage.Exceptions.DirectoryNotFoundException("Directory does not exist: " + path);
            }
            var ret = new IsoStoreFolder(name, this);

            return(ret);
        }
        /// <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(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);
            }
        }
Exemple #4
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);

            System.IO.FileAccess nativeFileAccess;
            if (fileAccess == FileAccess.Read)
            {
                nativeFileAccess = System.IO.FileAccess.Read;
            }
            else if (fileAccess == FileAccess.ReadAndWrite)
            {
                nativeFileAccess = System.IO.FileAccess.ReadWrite;
            }
            else
            {
                throw new ArgumentException("Unrecognized FileAccess value: " + fileAccess);
            }

            try
            {
                IsolatedStorageFileStream stream = _root.OpenFile(Path, FileMode.Open, nativeFileAccess, FileShare.Read);
                return(stream);
            }
            catch (IsolatedStorageException ex)
            {
                //	Check to see if error is because file does not exist, if so throw a more specific exception
                bool fileDoesntExist = false;
                try
                {
                    if (!_root.FileExists(Path))
                    {
                        fileDoesntExist = true;
                    }
                }
                catch { }
                if (fileDoesntExist)
                {
                    throw new PCLStorage.Exceptions.FileNotFoundException("File does not exist: " + Path, ex);
                }
                else
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// Checks whether a folder or file exists at the given location.
        /// </summary>
        /// <param name="name">The name of the file or folder to check for.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A task whose result is the result of the existence check.
        /// </returns>
        public async Task <ExistenceCheckResult> CheckExistsAsync(string name, CancellationToken cancellationToken)
        {
            Requires.NotNullOrEmpty(name, "name");

            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            var checkPath = PortablePath.Combine(Path, name);

            if (Root.FileExists(checkPath))
            {
                return(ExistenceCheckResult.FileExists);
            }
            else if (Root.DirectoryExists(checkPath))
            {
                return(ExistenceCheckResult.FolderExists);
            }
            else
            {
                return(ExistenceCheckResult.NotFound);
            }
        }
Exemple #6
0
        /// <summary>
        /// Gets a file from the App Bundle.  Returns null if the file does not exist.
        /// </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, or null if it does not exist.</returns>
        public static async Task <IFile> GetFileFromAppBundleAsync(string path, CancellationToken cancellationToken)
        {
            Requires.NotNullOrEmpty(path, "path");

            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            string bundlePath = NSBundle.MainBundle.ResourcePath;

            bundlePath = Path.Combine(bundlePath, path);
            FileSystemFile f = null;

            if (File.Exists(bundlePath))
            {
                f = new FileSystemFile(bundlePath);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("JK#237b# GetFileFromAppBundleAsync Error file (" + path + ") must be in the Resources folder marked as BundleResource.");
            }
            return(f);
        }
Exemple #7
0
        public async Task <IFileStats> GetFileStats(CancellationToken cancellationToken = new CancellationToken())
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            var localCreationTime   = _root.GetCreationTime(_path);
            var localLastWriteTime  = _root.GetLastWriteTime(_path);
            var localLastAccessTime = _root.GetLastAccessTime(_path);

            var fileStats = new FileSystemFileStats()
            {
                Name              = _name,
                Extension         = System.IO.Path.GetExtension(_name),
                CreationTime      = localCreationTime.DateTime,
                CreationTimeUTC   = localCreationTime.UtcDateTime,
                LastWriteTime     = localLastWriteTime.DateTime,
                LastWriteTimeUTC  = localLastWriteTime.UtcDateTime,
                LastAccessTime    = localLastAccessTime.DateTime,
                LastAccessTimeUTC = localLastAccessTime.UtcDateTime
            };

            return(fileStats);
        }
Exemple #8
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);

            try
            {
#if WINDOWS_PHONE
                //  Windows Phone (at least WP7) doesn't throw an error if you try to delete something that doesn't exist,
                //  so check for this manually for consistent behavior across platforms
                if (!_root.FileExists(Path))
                {
                    throw new PCLStorage.Exceptions.FileNotFoundException("File does not exist: " + Path);
                }
#endif
                _root.DeleteFile(Path);
            }
            catch (IsolatedStorageException ex)
            {
                //	Check to see if error is because file does not exist, if so throw a more specific exception
                bool fileDoesntExist = false;
                try
                {
                    if (!_root.FileExists(Path))
                    {
                        fileDoesntExist = true;
                    }
                }
                catch { }
                if (fileDoesntExist)
                {
                    throw new PCLStorage.Exceptions.FileNotFoundException("File does not exist: " + Path, ex);
                }
                else
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// Deletes this folder and all of its contents
        /// </summary>
        /// <returns>A task which will complete after the folder is deleted</returns>
        public async Task DeleteAsync(CancellationToken cancellationToken)
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            EnsureExists();

            if (string.IsNullOrEmpty(Path))
            {
                throw new IOException("Cannot delete root Isolated Storage folder.");
            }

            foreach (var subfolder in await GetFoldersAsync(cancellationToken).ConfigureAwait(false))
            {
                await subfolder.DeleteAsync(cancellationToken).ConfigureAwait(false);
            }

            foreach (var file in await GetFilesAsync(cancellationToken).ConfigureAwait(false))
            {
                await file.DeleteAsync(cancellationToken).ConfigureAwait(false);
            }

            Root.DeleteDirectory(Path);
        }
        public async Task <IFileStats> GetFileStats(CancellationToken cancellationToken = new CancellationToken())
        {
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            return(FileSystemFileStats.FromPath(Path));
        }
        /// <summary>
        /// Gets a file from the App Bundle.  Returns null if the file does not exist.
        /// </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, or null if it does not exist.</returns>
        public static async Task <IFile> GetFileFromAppBundleAsync(string assetFolderFilePath, CancellationToken cancellationToken)
        {
            Requires.NotNullOrEmpty(assetFolderFilePath, "assetFolderFilePath");
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);

            //I was not able to access files from the Assets folder like 'file://android_asset/'
            //Now I copy the file into a temp folder first
            //Hopefully somebody knows a better solution for this
            //Stream iStream = null;
            //try
            //{
            //    iStream = Application.Context.Assets.Open(path);
            //}
            //catch (Exception)
            //{
            //    System.Diagnostics.Debug.WriteLine("JK#237# GetFileFromAppBundleAsync Error file (" + path + ") must be in the assets folder marked as AndroidAsset.");
            //}
            //if (iStream == null)
            //{
            //    return null;
            //}
            var tempPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

            tempPath = System.IO.Path.Combine(tempPath, "appbundlefilestempfolder");
            if (System.IO.Directory.Exists(tempPath) == false)
            {
                System.IO.Directory.CreateDirectory(tempPath);
            }
            var path = System.IO.Path.GetFileName(assetFolderFilePath); //No subfolder inside the tempfolder

            tempPath = System.IO.Path.Combine(tempPath, path);
            //Files from the app package can't change so there is no need to copy them again
            if (System.IO.File.Exists(tempPath) == false)
            {
                try
                {
                    using (var br = new BinaryReader(Application.Context.Assets.Open(assetFolderFilePath)))
                    {
                        using (var bw = new BinaryWriter(new FileStream(tempPath, FileMode.Create)))
                        {
                            byte[] buffer = new byte[2048];
                            int    length = 0;
                            while ((length = br.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                bw.Write(buffer, 0, length);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("JK#237# GetFileFromAppBundleAsync Error file (" + path + ") must be in the assets folder marked as AndroidAsset. " + e.Message);
                }
                //var oStream = new FileOutputStream(tempPath);
                //byte[] buffer = new byte[2048];
                //int length = 2048;
                //while (iStream.Read(buffer, 0, length) > 0)
                //{
                //    oStream.Write(buffer, 0, length);
                //}
                //oStream.Flush();
                //oStream.Close();
                //iStream.Close();
            }
            if (System.IO.File.Exists(tempPath) == false)
            {
                return(null);
            }
            return(new FileSystemFile(tempPath));
        }