private SQLiteConnection CreateSQLiteConnection(string nativeDbPath, CreationCollisionOption creationCollisionOption)
        {
            if (string.IsNullOrEmpty(nativeDbPath) || databaseNameProvider == null || fileService == null || sqlitePlatformProvider == null) return null;

            try
            {
                createSqlConnectionResetEvent.WaitOne();

                if (creationCollisionOption == CreationCollisionOption.OpenIfExists && SqliteDbConnection != null)
                {
                    return SqliteDbConnection;
                }

                SqliteDbConnection = new SQLiteConnection(sqlitePlatformProvider.SqLitePlatform, nativeDbPath, SQLiteOpenFlags.Create | SQLiteOpenFlags.ReadWrite);
                return SqliteDbConnection;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
            finally
            {
                createSqlConnectionResetEvent.Set();
            }

            return null;
        }
        /// <summary>
        /// Writes a string to a text file.
        /// </summary>
        /// <param name="text">The text to write.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="folder">The folder.</param>
        /// <param name="options">
        /// The enum value that determines how responds if the fileName is the same
        /// as the name of an existing file in the current folder. Defaults to ReplaceExisting.
        /// </param>
        /// <returns></returns>
        public static async Task SaveAsync(
            this string text,
            string fileName,
            StorageFolder folder = null,
            CreationCollisionOption options = CreationCollisionOption.ReplaceExisting)
        {
            folder = folder ?? ApplicationData.Current.LocalFolder;
            var file = await folder.CreateFileAsync(
                fileName,
                options);
            using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var outStream = fs.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outStream))
                    {
                        if (text != null)
                            dataWriter.WriteString(text);

                        await dataWriter.StoreAsync();
                        dataWriter.DetachStream();
                    }

                    await outStream.FlushAsync();
                }
            }
        }
        public static async Task<StorageFolder> TryCreateFolderAsync(this StorageFolder storageFolder, string name, CreationCollisionOption options = CreationCollisionOption.OpenIfExists)
        {
            StorageFolder folder = null;
            try
            {
                folder = await storageFolder.CreateFolderAsync(name, options);
            }
            catch
            {
            }

            return folder;
        }
        /// <summary>
        /// Creates a file in this folder
        /// </summary>
        /// <param name="desiredName">The name of the file to create</param>
        /// <param name="option">Specifies how to behave if the specified file already exists</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The newly created file</returns>
        public async Task<IFile> CreateFileAsync(string desiredName, CreationCollisionOption option, CancellationToken cancellationToken)
        {
            Requires.NotNullOrEmpty(desiredName, "desiredName");

            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);
            EnsureExists();

            string nameToUse = desiredName;
            string newPath = System.IO.Path.Combine(Path, nameToUse);
            if (File.Exists(newPath))
            {
                if (option == CreationCollisionOption.GenerateUniqueName)
                {
                    string desiredRoot = System.IO.Path.GetFileNameWithoutExtension(desiredName);
                    string desiredExtension = System.IO.Path.GetExtension(desiredName);
                    for (int num = 2; File.Exists(newPath); num++)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        nameToUse = desiredRoot + " (" + num + ")" + desiredExtension;
                        newPath = System.IO.Path.Combine(Path, nameToUse);
                    }
                    InternalCreateFile(newPath);
                }
                else if (option == CreationCollisionOption.ReplaceExisting)
                {
                    File.Delete(newPath);
                    InternalCreateFile(newPath);
                }
                else if (option == CreationCollisionOption.FailIfExists)
                {
                    throw new IOException("File already exists: " + newPath);
                }
                else if (option == CreationCollisionOption.OpenIfExists)
                {
                    //	No operation
                }
                else
                {
                    throw new ArgumentException("Unrecognized CreationCollisionOption: " + option);
                }
            }
            else
            {
                //	Create file
                InternalCreateFile(newPath);
            }

            var ret = new FileSystemFile(newPath);
            return ret;
        }
        private async Task<SQLiteConnection> CreateSQLiteConnection(CreationCollisionOption creationCollisionOption)
        {
            if (databaseNameProvider == null || fileService == null || sqlitePlatformProvider == null) return null;

            try
            {
                return CreateSQLiteConnection(await fileService.RetrieveNativePath(databaseNameProvider.DatabaseName), creationCollisionOption);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

            return null;
        }
Beispiel #6
0
        public static async Task SaveImageAsyncFromUri(string filename, StorageFolder folder, Uri url, CreationCollisionOption option)
        {

            if(folder != null)
            {
                StorageFile file = await folder.CreateFileAsync(filename, option);

                HttpClient client = new HttpClient();
                byte[] fileContent = await client.GetByteArrayAsync(url);

                Stream fileStream = await file.OpenStreamForWriteAsync();
                fileStream.Write(fileContent, 0, fileContent.Length);
                fileStream.Flush();
                fileStream.Dispose();
            }
        }
        /// <summary>
        /// Saves the WriteableBitmap to a file in the given folder with the given file name.
        /// </summary>
        /// <param name="writeableBitmap">The writeable bitmap.</param>
        /// <param name="storageFolder">The storage folder.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="options">
        /// The enum value that determines how responds if the fileName is the same
        /// as the name of an existing file in the current folder. Defaults to ReplaceExisting.
        /// </param>
        /// <returns></returns>
        public static async Task<StorageFile> SaveToFile(
            this WriteableBitmap writeableBitmap,
            StorageFolder storageFolder,
            string fileName,
            CreationCollisionOption options = CreationCollisionOption.ReplaceExisting)
        {
            StorageFile outputFile =
                await storageFolder.CreateFileAsync(
                    fileName,
                    options);

            Guid encoderId;

            var ext = Path.GetExtension(fileName);

            if (new[] { ".bmp", ".dib" }.Contains(ext))
            {
                encoderId = BitmapEncoder.BmpEncoderId;
            }
            else if (new[] { ".tiff", ".tif" }.Contains(ext))
            {
                encoderId = BitmapEncoder.TiffEncoderId;
            }
            else if (new[] { ".gif" }.Contains(ext))
            {
                encoderId = BitmapEncoder.GifEncoderId;
            }
            else if (new[] { ".jpg", ".jpeg", ".jpe", ".jfif", ".jif" }.Contains(ext))
            {
                encoderId = BitmapEncoder.JpegEncoderId;
            }
            else if (new[] { ".hdp", ".jxr", ".wdp" }.Contains(ext))
            {
                encoderId = BitmapEncoder.JpegXREncoderId;
            }
            else //if (new [] {".png"}.Contains(ext))
            {
                encoderId = BitmapEncoder.PngEncoderId;
            }

            await writeableBitmap.SaveToFile(outputFile, encoderId);

            return outputFile;
        }
        public static async Task<StorageFile> CreateFileAsync(string path, StorageFolder folder,
          CreationCollisionOption option = CreationCollisionOption.OpenIfExists)
        {
            if (path.StartsWith("/") || path.StartsWith("\\"))
                path = path.Substring(1);
            var parts = path.Split('/');

            var fileName = parts.Last();

            if (parts.Length > 1)
            {
                folder =
                    await
                        EnsureFolderExistsAsync(path.Substring(0, path.Length - fileName.Length), folder)
                            .ConfigureAwait(false);
            }

            return await folder.CreateFileAsync(fileName, option).AsTask().ConfigureAwait(false);
        }
Beispiel #9
0
 /// <summary>
 /// Creates a file in this folder
 /// </summary>
 /// <param name="desiredName">The name of the file to create</param>
 /// <param name="option">Specifies how to behave if the specified file already exists</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The newly created file</returns>
 public async Task<IFile> CreateFileAsync(string desiredName, CreationCollisionOption option, CancellationToken cancellationToken)
 {
     Requires.NotNullOrEmpty(desiredName, "desiredName");
     await EnsureExistsAsync(cancellationToken).ConfigureAwait(false);
     StorageFile wrtFile;
     try
     {
         wrtFile = await _wrappedFolder.CreateFileAsync(desiredName, GetWinRTCreationCollisionOption(option)).AsTask(cancellationToken).ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         if (ex.HResult == WinRTFile.FILE_ALREADY_EXISTS)
         {
             //  File already exists (and potentially other failures, not sure what the HResult represents)
             throw new IOException(ex.Message, ex);
         }
         throw;
     }
     return new WinRTFile(wrtFile);
 }
 public async Task <StorageFile> CreateFileAsync(string name, CreationCollisionOption options = CreationCollisionOption.OpenIfExists)
 {
     return(await CurrentFolder?.TryCreateFileAsync(name, options));
 }
Beispiel #11
0
            public override IAsyncOperation <StorageFolder> CreateFolderAsync(string folderName, CreationCollisionOption option) =>
            AsyncOperation.FromTask(async ct =>
            {
                if (folderName.Contains("\""))
                {
                    throw new FileNotFoundException("The filename, directory name, or volume label syntax is incorrect.", folderName);
                }

                var folderHandleGuidString = await WebAssemblyRuntime.InvokeAsync($"{_jsType}.CreateFolderAsync(\"{_id}\", \"{folderName}\")");

                var guid = new Guid(folderHandleGuidString);

                var storageFolder = GetFolderFromNativePathAsync(Path, guid);

                return(storageFolder);
            });
Beispiel #12
0
 /// <inheritdoc />
 public Task <IFolder> CreateFolderAsync(string desiredName, CreationCollisionOption option, CancellationToken cancellationToken = default(CancellationToken)) => _folder.CreateFolderAsync(desiredName, option, cancellationToken);
 public async Task<StorageFile> CreateFile(StorageFolder folder, string filename, CreationCollisionOption option)
 {
     return await folder.CreateFileAsync(filename, option);
 }
        /// <summary>
        /// Creates a subfolder in this folder
        /// </summary>
        /// <param name="desiredName">The name of the folder to create</param>
        /// <param name="option">Specifies how to behave if the specified folder already exists</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The newly created folder</returns>
        public async Task<IFolder> CreateFolderAsync(string desiredName, CreationCollisionOption option, CancellationToken cancellationToken)
        {
            Requires.NotNullOrEmpty(desiredName, "desiredName");

            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);
            EnsureExists();

            string nameToUse = desiredName;
            string newPath = System.IO.Path.Combine(Path, nameToUse);
            if (Root.DirectoryExists(newPath))
            {
                if (option == CreationCollisionOption.GenerateUniqueName)
                {
                    for (int num = 2; Root.DirectoryExists(newPath); num++)
                    {
                        nameToUse = desiredName + " (" + num + ")";
                        newPath = System.IO.Path.Combine(Path, nameToUse);
                    }
                    Root.CreateDirectory(newPath);
                }
                else if (option == CreationCollisionOption.ReplaceExisting)
                {
                    IsoStoreFolder folderToDelete = new IsoStoreFolder(nameToUse, this);
                    await folderToDelete.DeleteAsync(cancellationToken).ConfigureAwait(false);
                    Root.CreateDirectory(newPath);
                }
                else if (option == CreationCollisionOption.FailIfExists)
                {
                    throw new IOException("Directory already exists: " + newPath);
                }
                else if (option == CreationCollisionOption.OpenIfExists)
                {
                    //	No operation
                }
                else
                {
                    throw new ArgumentException("Unrecognized CreationCollisionOption: " + option);
                }
            }
            else
            {
                Root.CreateDirectory(newPath);
            }

            var ret = new IsoStoreFolder(nameToUse, this);
            return ret;
        }
Beispiel #15
0
 Windows.Storage.CreationCollisionOption GetWinRTCreationCollisionOption(CreationCollisionOption option)
 {
     if (option == CreationCollisionOption.GenerateUniqueName)
     {
         return Windows.Storage.CreationCollisionOption.GenerateUniqueName;
     }
     else if (option == CreationCollisionOption.ReplaceExisting)
     {
         return Windows.Storage.CreationCollisionOption.ReplaceExisting;
     }
     else if (option == CreationCollisionOption.FailIfExists)
     {
         return Windows.Storage.CreationCollisionOption.FailIfExists;
     }
     else if (option == CreationCollisionOption.OpenIfExists)
     {
         return Windows.Storage.CreationCollisionOption.OpenIfExists;
     }
     else
     {
         throw new ArgumentException("Unrecognized CreationCollisionOption value: " + option);
     }
 }
Beispiel #16
0
 private static async Task<Windows.Storage.StorageFile> CreateFileAsync(string key,
     FilePathKind fileKind = FilePathKind.DataFolder,
     CreationCollisionOption option = CreationCollisionOption.OpenIfExists)
 {
     switch (fileKind)
     {
         case FilePathKind.DataFolder:
             return await ApplicationData.Current.LocalFolder.CreateFileAsync(key, option);
         case FilePathKind.InstalledFolder:
             return await Package.Current.InstalledLocation.CreateFileAsync(key, option);
         case FilePathKind.AbsolutePath:
         default:
             throw new NotSupportedException(fileKind.ToString());
     }
 }
Beispiel #17
0
        public override IAsyncOperation <BaseStorageFolder> CreateFolderAsync(string desiredName, CreationCollisionOption options)
        {
            return(AsyncInfo.Run <BaseStorageFolder>(async(cancellationToken) =>
            {
                var hFile = NativeFileOperationsHelper.OpenFileForRead(ContainerPath, true);
                if (hFile.IsInvalid)
                {
                    return null;
                }
                using (ZipFile zipFile = new ZipFile(new FileStream(hFile, FileAccess.ReadWrite)))
                {
                    zipFile.IsStreamOwner = true;

                    var znt = new ZipNameTransform(ContainerPath);
                    var zipDesiredName = znt.TransformDirectory(System.IO.Path.Combine(Path, desiredName));
                    var entry = zipFile.GetEntry(zipDesiredName);

                    zipFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Direct));
                    if (entry != null)
                    {
                        if (options != CreationCollisionOption.ReplaceExisting)
                        {
                            zipFile.AbortUpdate();
                            return null;
                        }
                        zipFile.Delete(entry);
                    }
                    zipFile.AddDirectory(zipDesiredName);
                    zipFile.CommitUpdate();

                    var wnt = new WindowsNameTransform(ContainerPath);
                    return new ZipStorageFolder(wnt.TransformFile(zipDesiredName), ContainerPath)
                    {
                        ZipEncoding = ZipEncoding
                    };
                }
            }));
        }
 public async Task <IFolder> CreateFolderAsync(string desiredName, CreationCollisionOption option,
                                               CancellationToken cancellationToken = new CancellationToken())
 {
     throw new NotImplementedException();
 }
Beispiel #19
0
        public static async Task <StorageFolder> CreateFolder(string path, IStorageFolder rootFolder = null, CreationCollisionOption options = CreationCollisionOption.FailIfExists)
        {
            var localFolder = rootFolder ?? ApplicationData.Current.LocalFolder;

            return(await localFolder.CreateFolderAsync(path, options));
        }
Beispiel #20
0
        private static async Task <StorageFile> CreateFileAsync(string path, StorageFolder folder, CreationCollisionOption option = CreationCollisionOption.OpenIfExists)
        {
            var parts = path.Split('/');

            var fileName = parts.Last();

            if (parts.Length > 1)
            {
                folder = await EnsureFolderExistsAsync(path.Substring(0, path.Length - fileName.Length), folder).ConfigureAwait(false);
            }

            return(await folder.CreateFileAsync(fileName, option).AsTask().ConfigureAwait(false));
        }
 Task <IFolder> PlatformCreateFolder(IFolder destination, string name, CreationCollisionOption option)
 {
     throw new NotImplementedException();
 }
Beispiel #22
0
 public StorageFilesCopier(List<StorageFile> files, StorageFolder folder, CreationCollisionOption collisionoption=CreationCollisionOption.GenerateUniqueName)
 {
     this.Files = files;
     this.Folder = folder;
     this.CollisionOption = collisionoption;
 }
Beispiel #23
0
 public StorageFilesCopier() 
 {
     this.Files = new List<StorageFile>();
     this.Folder = null;
     this.CollisionOption = CreationCollisionOption.GenerateUniqueName;
 }
Beispiel #24
0
        public static async Task <StorageFile> SaveFileAsync(this StorageFolder folder, byte[] content, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            if (String.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException("ExceptionSettingsStorageExtensionsFileNameIsNullOrEmpty".GetLocalized(), nameof(fileName));
            }

            StorageFile storageFile = await folder.CreateFileAsync(fileName, options);

            await FileIO.WriteBytesAsync(storageFile, content);

            return(storageFile);
        }
		private async Task<StorageFile> CreateStorageFileFromPath(string path, CreationCollisionOption createCollisionOption)
		{
			if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
			var folder = await GetStorageFolderFromFilePath(path);
			// '.' chars results in an NotAuthorizedAccessException
			var file = await folder.CreateFileAsync(Path.GetFileName(path).Replace('.', '_'), createCollisionOption);
			return file;
		}
Beispiel #26
0
 /// <summary>
 /// Creates a subfolder in this folder
 /// </summary>
 /// <param name="folder">Target folder</param>
 /// <param name="desiredName">The name of the folder to create</param>
 /// <param name="option">Specifies how to behave if the specified folder already exists</param>
 /// <returns>The newly created folder</returns>
 public static IFolder CreateFolder(this IFolder folder, string desiredName, CreationCollisionOption option)
 {
     return(folder.CreateFolderAsync(desiredName, option).Result);
 }
 public async Task<StorageFile> CreateFileAsync(IBuffer buffer, string name, CreationCollisionOption options = CreationCollisionOption.OpenIfExists)
 {
     var file = await CreateFileAsync(name, options);
     await file.TryWriteBufferAsync(buffer);
     return file;
 }
Beispiel #28
0
            public override async Task <StorageFolder> CreateFolderAsync(string folderName, CreationCollisionOption option, CancellationToken token)
            {
                using (_nsUrl.BeginSecurityScopedAccess())
                {
                    var path       = IOPath.Combine(Path, folderName);
                    var actualName = folderName;

                    switch (option)
                    {
                    case CreationCollisionOption.FailIfExists:
                        if (Directory.Exists(path) || File.Exists(path))
                        {
                            throw new UnauthorizedAccessException("There is already an item with the same name.");
                        }
                        break;

                    case CreationCollisionOption.GenerateUniqueName:
                        actualName = await FindAvailableNumberedFolderNameAsync(folderName);

                        break;

                    case CreationCollisionOption.OpenIfExists:
                        if (File.Exists(path))
                        {
                            throw new UnauthorizedAccessException("There is already a file with the same name.");
                        }
                        break;

                    case CreationCollisionOption.ReplaceExisting:
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }

                        if (File.Exists(path))
                        {
                            throw new UnauthorizedAccessException("There is already a file with the same name.");
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(option));
                    }

                    var actualPath = IOPath.Combine(Path, actualName);
                    if (!Directory.Exists(actualPath))
                    {
                        Directory.CreateDirectory(actualPath);
                    }

                    return(GetFromSecurityScopedUrl(_nsUrl.Append(actualName, true), Owner));
                }
            }
 private void GetCacheFile(CreationCollisionOption option)
 {
     workingFile = workingFolder.CreateFileAsync(nameof(PicLibFolderScanService) + ".cache", option);
 }
Beispiel #30
0
            public override async Task <StorageFile> CreateFileAsync(string desiredName, CreationCollisionOption options, CancellationToken cancellationToken)
            {
                using var _ = _nsUrl.BeginSecurityScopedAccess();
                var path       = IOPath.Combine(Path, desiredName);
                var actualName = desiredName;

                switch (options)
                {
                case CreationCollisionOption.FailIfExists:
                    if (Directory.Exists(path) || File.Exists(path))
                    {
                        throw new UnauthorizedAccessException("There is already an item with the same name.");
                    }
                    break;

                case CreationCollisionOption.GenerateUniqueName:
                    actualName = await FindAvailableNumberedFileNameAsync(desiredName);

                    break;

                case CreationCollisionOption.OpenIfExists:
                    if (Directory.Exists(path))
                    {
                        throw new UnauthorizedAccessException("There is already a folder with the same name.");
                    }
                    break;

                case CreationCollisionOption.ReplaceExisting:
                    if (Directory.Exists(path))
                    {
                        throw new UnauthorizedAccessException("There is already a folder with the same name.");
                    }

                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(options));
                }

                var actualPath = IOPath.Combine(Path, actualName);

                if (!File.Exists(actualPath))
                {
                    File.Create(actualPath).Close();
                }

                return(StorageFile.GetFromSecurityScopedUrl(_nsUrl.Append(actualName, false), Owner));
            }
        /// <summary>
        /// Retrieves a stream for writing from a file in the specified parent folder.
        /// </summary>
        /// <param name="rootDirectory">The Windows Runtime IStorageFolder object that contains the file to write to.</param>
        /// <param name="relativePath">The path, relative to the root folder, to the file to write to.</param>
        /// <param name="creationCollisionOption"></param>
        /// <returns></returns>
        public static Task<Stream> OpenStreamForWriteAsync(this IStorageFolder rootDirectory, string relativePath, CreationCollisionOption creationCollisionOption)
        {
#if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE
            return WindowsRuntimeStorageExtensions.OpenStreamForWriteAsync((global::Windows.Storage.StorageFolder)((StorageFolder)rootDirectory), relativePath, (global::Windows.Storage.CreationCollisionOption)((int)creationCollisionOption));
#elif __ANDROID__ || __UNIFIED__ || WIN32
            string newPath = Path.Combine(rootDirectory.Path, relativePath);
            return Task.FromResult<Stream>(global::System.IO.File.OpenWrite(newPath));
#else
            throw new PlatformNotSupportedException();
#endif
        }
Beispiel #32
0
    // Overload: Override the default file overwrite setting at the class level for this specific file
    public async Task <string> DownloadStorageBlockBlobBasicOperationAsync(string MediaFile, bool overwrite)
    {
        try
        {
            // Create a blob client for interacting with the blob service.
            CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();

            // Create a container for organizing blobs within the storage account.
            WriteLine("Opening Blob Container in Azure Storage.");
            CloudBlobContainer container = blobClient.GetContainerReference(BlobContainerName);
            try
            {
                await container.CreateIfNotExistsAsync();
            }
            catch (StorageException)
            {
                WriteLine("If you are running with the default configuration please make sure you have started the storage emulator. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample.");
                throw;
            }

            // Access a specific blob in the container
            WriteLine("Getting Specific Blob in Container.");

            // We assume the client app knows which asset to download by name
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(MediaFile);

            if (blockBlob != null)
            {
                // Download a blob to your file system
                string path = "";
                WriteLine(string.Format("Downloading Blob from {0}, please wait...", blockBlob.Uri.AbsoluteUri));
                string fileName = MediaFile; // string.Format("CopyOf{0}", MediaFile);

                bool fileExists = false;
#if WINDOWS_UWP
                StorageFolder storageFolder = ApplicationData.Current.TemporaryFolder;
                StorageFile   sf;
                try
                {
                    CreationCollisionOption collisionoption = (overwrite ? CreationCollisionOption.ReplaceExisting : CreationCollisionOption.FailIfExists);
                    sf = await storageFolder.CreateFileAsync(fileName, collisionoption);

                    fileExists = false; // if the file existed but we were allowed to overwrite it, let's treat it as if it didn't exist
                    path       = sf.Path;
                }
                catch (Exception)
                {
                    // The file already exists and we're not supposed to overwrite it
                    fileExists = true;
                    sf         = await storageFolder.GetFileAsync(fileName); // Necessary to avoid a compilation error below
                }
#else
                path       = Path.Combine(Application.temporaryCachePath, fileName);
                fileExists = File.Exists(path);
#endif
                if (fileExists)
                {
                    if (overwrite)
                    {
                        WriteLine(string.Format("Already exists. Deleting file {0}", fileName));
#if WINDOWS_UWP
                        // Nothing to do here in UWP, we already Replaced it when we created the StorageFile
#else
                        File.Delete(path);
#endif
                    }
                    else
                    {
                        WriteLine(string.Format("File {0} already exists and overwriting is disabled. Download operation cancelled.", fileName));
                        return(path);
                    }
                }
                // Start the timer to measure performance
                var sw = Stopwatch.StartNew();
#if WINDOWS_UWP
                await blockBlob.DownloadToFileAsync(sf);
#else
                await blockBlob.DownloadToFileAsync(path, FileMode.Create);
#endif
                // Stop the timer and report back on completion + performance
                sw.Stop();
                TimeSpan time = sw.Elapsed;
                WriteLine(string.Format("Blob file downloaded to {0} in {1}s.", path, time.TotalSeconds.ToString()));

                return(path);
            }
            else
            {
                WriteLine(string.Format("File {0} not found in blob {1}.", MediaFile, blockBlob.Uri.AbsoluteUri));
                return(string.Empty);
            }
        }
        catch (Exception ex)
        {
            // Woops!
            WriteLine(string.Format("Error while downloading file {0}.", MediaFile));
            WriteLine("Error: " + ex.ToString());
            WriteLine("Error: " + ex.InnerException.ToString());
            return(string.Empty);
        }
    }
    /// <summary>
    /// Creates a <see cref="StorageFolder"/> into a specified <see cref="StorageFolder"/>
    /// </summary>
    /// <param name="storageFolder">the folder where the function has to check</param>
    /// <param name="folderName">the folder name</param>
    /// <param name="creationOption">the <see cref="CreationCollisionOption"/></param>
    /// <returns>true in case of success. false otherwise</returns>
    public async Task<bool> CreateFolder(StorageFolder storageFolder, string folderName, CreationCollisionOption creationOption)
    {
      using (await InstanceLock.LockAsync())
      {
        var isCreated = true;

        try
        {
          folderName = folderName.Replace("/", "\\");
          var folder = await storageFolder.CreateFolderAsync(Path.GetDirectoryName(folderName), creationOption);
        }
        catch
        {
          isCreated = false;
        }

        return isCreated;
      }
    }
Beispiel #34
0
    // Overload: Override the default file overwrite setting at the class level for this specific file
    public async Task <string> DownloadStorageBlockBlobSegmentedOperationAsync(string MediaFile, bool overwrite)
    {
        try
        {
            // Create a blob client for interacting with the blob service.
            CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();

            // Create a container for organizing blobs within the storage account.
            WriteLine("Opening Blob Container in Azure Storage.");
            CloudBlobContainer container = blobClient.GetContainerReference(BlobContainerName);
            try
            {
                await container.CreateIfNotExistsAsync();
            }
            catch (StorageException)
            {
                WriteLine("If you are running with the default configuration please make sure you have started the storage emulator. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample.");
                throw;
            }

            // Access a specific blob in the container
            WriteLine("Get Specific Blob in Container and its size");

            CloudBlockBlob blockBlob   = container.GetBlockBlobReference(MediaFile);
            int            segmentSize = SegmentSizeKB * 1024; // SegmentSizeKB is set in the inspector chunk

            if (blockBlob != null)
            {
                // Obtain the size of the blob
                await blockBlob.FetchAttributesAsync();

                long  blobSize            = blockBlob.Properties.Length;
                long  blobLengthRemaining = blobSize;
                float completion          = 0f;
                long  startPosition       = 0;
                WriteLine("3. Blob size (bytes):" + blobLengthRemaining.ToString());

                // Download a blob to your file system
                string path = "";
                WriteLine(string.Format("Downloading Blob from {0}, please wait...", blockBlob.Uri.AbsoluteUri));
                string fileName = MediaFile; // string.Format("CopyOf{0}", MediaFile);

                bool fileExists = false;
#if WINDOWS_UWP
                StorageFolder storageFolder = ApplicationData.Current.TemporaryFolder;
                StorageFile   sf;
                try
                {
                    CreationCollisionOption collisionoption = (overwrite ? CreationCollisionOption.ReplaceExisting : CreationCollisionOption.FailIfExists);
                    sf = await storageFolder.CreateFileAsync(fileName, collisionoption);

                    fileExists = false; // if the file existed but we were allowed to overwrite it, let's treat it as if it didn't exist
                }
                catch (Exception)
                {
                    // The file already exists and we're not supposed to overwrite it
                    fileExists = true;
                    sf         = await storageFolder.GetFileAsync(fileName); // Necessary to avoid a compilation error below
                }
                path = sf.Path;
#else
                path       = Path.Combine(Application.temporaryCachePath, fileName);
                fileExists = File.Exists(path);
#endif
                if (fileExists)
                {
                    if (overwrite)
                    {
                        WriteLine(string.Format("Already exists. Deleting file {0}", fileName));
#if WINDOWS_UWP
                        // Nothing to do here in UWP, we already Replaced it when we created the StorageFile
#else
                        File.Delete(path);
#endif
                    }
                    else
                    {
                        WriteLine(string.Format("File {0} already exists and overwriting is disabled. Download operation cancelled.", fileName));
                        return(path);
                    }
                }

                ProgressBar.AddDownload();
#if WINDOWS_UWP
                var fs = await sf.OpenAsync(FileAccessMode.ReadWrite);
#else
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
#endif
                // Start the timer to measure performance
                var sw = Stopwatch.StartNew();
                do
                {
                    long   blockSize    = Math.Min(segmentSize, blobLengthRemaining);
                    byte[] blobContents = new byte[blockSize];
                    using (MemoryStream ms = new MemoryStream())
                    {
                        await blockBlob.DownloadRangeToStreamAsync(ms, (long)startPosition, blockSize);

                        ms.Position = 0;
                        ms.Read(blobContents, 0, blobContents.Length);
#if WINDOWS_UWP
                        fs.Seek((ulong)startPosition);
                        await fs.WriteAsync(blobContents.AsBuffer());
#else
                        fs.Position = startPosition;
                        fs.Write(blobContents, 0, blobContents.Length);
#endif
                    }
                    completion = (float)startPosition / (float)blobSize;
                    WriteLine("Completed: " + (completion).ToString("P"));
                    ProgressBar.Value    = (completion * 100);
                    startPosition       += blockSize;
                    blobLengthRemaining -= blockSize;
                }while (blobLengthRemaining > 0);
                WriteLine("Completed: 100.00%");
                ProgressBar.Value = 100;
                ProgressBar.RemoveDownload();
#if !WINDOWS_UWP
                // Required for Mono & .NET or we'll get a file IO access violation the next time we try to access it
                fs.Close();
#else
                fs.Dispose();
#endif
                fs = null;

                // Stop the timer and report back on completion + performance
                sw.Stop();
                TimeSpan time = sw.Elapsed;
                WriteLine(string.Format("5. Blob file downloaded to {0} in {1}s", path, time.TotalSeconds.ToString()));
                return(path);
            }
            else
            {
                WriteLine(string.Format("3. File {0} not found in blob {1}", MediaFile, blockBlob.Uri.AbsoluteUri));
                return(string.Empty);
            }
        }
        catch (Exception ex)
        {
            // Woops!
            WriteLine(string.Format("Error while downloading file {0}", MediaFile));
            WriteLine("Error: " + ex.ToString());
            WriteLine("Error: " + ex.InnerException.ToString());
            return(string.Empty);
        }
    }
Beispiel #35
0
 public static async Task <IFile> CreateFileAsync(string path,
                                                  StorageStrategy location       = StorageStrategy.Local,
                                                  CreationCollisionOption option = CreationCollisionOption.OpenIfExists)
 {
     return(await CreateFileAsync(path, GetFolderFromStrategy(location), option));
 }
 public static IAsyncOperation <StorageFile> CreateFileAsync(string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting)
 {
     return(ApplicationData.Current.LocalFolder.CreateFileAsync($"{ApplicationSettings.Current.SelectedAccount}\\{fileName}", options));
 }
Beispiel #37
0
        public static async Task <StorageFile> SaveFileAsync(this StorageFolder folder, byte[] content, string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException("File name is null or empty. Specify a valid file name", "fileName");
            }

            var storageFile = await folder.CreateFileAsync(fileName, options);

            await FileIO.WriteBytesAsync(storageFile, content);

            return(storageFile);
        }
 public static IAsyncOperation <StorageFile> CreateTempFileAsync(string fileName, CreationCollisionOption options = CreationCollisionOption.ReplaceExisting)
 {
     return(ApplicationData.Current.LocalFolder.CreateFileAsync($"temp\\{fileName}", options));
 }
        public async Task <StorageFile> CreateFileAsync(IRandomAccessStream stream, string name, CreationCollisionOption options = CreationCollisionOption.OpenIfExists)
        {
            var file = await CreateFileAsync(name, options);

            await file.TryWriteStreamAsync(stream);

            return(file);
        }
Beispiel #40
0
        public static async Task <StorageFile> CreateNewFileInBackupFolderAsync(string fileName, CreationCollisionOption collisionOption, string backupFolderName)
        {
            StorageFolder backupFolder = await GetBackupFolderAsync(backupFolderName);

            return(await backupFolder.CreateFileAsync(fileName, collisionOption));
        }
Beispiel #41
0
        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);
        }
 public static async Task <StorageFile> CreateFile(StorageFolder folder, string fileName, CreationCollisionOption option = CreationCollisionOption.ReplaceExisting)
 {
     return(await folder.CreateFileAsync(fileName, option));
 }
Beispiel #43
0
 public static async Task<IFile> CreateFileAsync(string path,
     StorageStrategy location = StorageStrategy.Local,
     CreationCollisionOption option = CreationCollisionOption.OpenIfExists)
 {
     return await CreateFileAsync(path, GetFolderFromStrategy(location), option);
 }
Beispiel #44
0
 public abstract IAsyncOperation <BaseStorageFolder> CreateFolderAsync(string desiredName, CreationCollisionOption options);
 //Create File for Recording on Phone/Storage
 private static async Task<StorageFile> GetScreenRecVdo(CreationCollisionOption creationCollisionOption = CreationCollisionOption.ReplaceExisting)
 {
     return await KnownFolders.SavedPictures.CreateFileAsync("VehicleDetails.mp4", creationCollisionOption);
 }
Beispiel #46
0
 IAsyncOperation <StorageFolder> IStorageFolder.CreateFolderAsync(string desiredName, CreationCollisionOption options)
 {
     return(AsyncInfo.Run(async(cancellationToken) =>
     {
         return await(await CreateFolderAsync(desiredName, options)).ToStorageFolderAsync();
     }));
 }
 public async Task<StorageFile> CreateFileAsync(Stream stream, string name, CreationCollisionOption options = CreationCollisionOption.OpenIfExists)
 {
     var file = await CreateFileAsync(name, options);
     await file.TryWriteStreamAsync(stream);
     return file;
 }
Beispiel #48
0
 public FilePersistence()
 {
     _options = CreationCollisionOption.OpenIfExists;
     _folder  = ApplicationData.Current.LocalFolder;
 }
        public static Task<Stream> OpenStreamForWriteAsync(this IStorageFolder rootDirectory, String relativePath,
                                                           CreationCollisionOption creationCollisionOption)
        {
            if (rootDirectory == null)
                throw new ArgumentNullException("rootDirectory");

            if (relativePath == null)
                throw new ArgumentNullException("relativePath");

            if (String.IsNullOrWhiteSpace(relativePath))
                throw new ArgumentException(SR.Argument_RelativePathMayNotBeWhitespaceOnly, "relativePath");

            Contract.Ensures(Contract.Result<Task<Stream>>() != null);
            Contract.EndContractBlock();

            return OpenStreamForWriteAsyncCore(rootDirectory, relativePath, creationCollisionOption);
        }
    /// <summary>
    /// Writes a <see cref="string"/> into a file located into a specified <see cref="StorageFolder"/>
    /// </summary>
    /// <param name="storageFolder">the folder where the function has to check</param>
    /// <param name="fileName">the file name</param>
    /// <param name="fileContent">the file content</param>
    /// <param name="creationOption">the <see cref="CreationCollisionOption"/></param>
    /// <returns>true in case of success. false otherwise</returns>
    public async Task<bool> WriteFile(StorageFolder storageFolder, string fileName, string fileContent, CreationCollisionOption creationOption)
    {
      using (await InstanceLock.LockAsync())
      {
        var isWritten = true;

        try
        {
          fileName = fileName.Replace("/", "\\");
          var file = await storageFolder.CreateFileAsync(fileName, creationOption);
          await FileIO.WriteTextAsync(file, fileContent);
        }
        catch
        {
          isWritten = false;
        }

        return isWritten;
      }
    }
		private async Task<Stream> CreateStream(Guid trackId, CreationCollisionOption creationCollisionOption = CreationCollisionOption.OpenIfExists)
		{
			Stream stream = null;
			bool isUnauthorizedAccess = false;
			try
			{
                await LocalStorage.ReleaseCacheAsync(24100224);
                await IOUtilities.WrapSharingViolations(async () =>
				{
					IStorageFolder storageFolder = await LocalStorage.GetTempFolderAsync();
                    var storageFile = await storageFolder.CreateFileAsync(trackId.ToString(), creationCollisionOption) as StorageFile;
					IRandomAccessStream windowsRuntimeStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);
					stream = windowsRuntimeStream.AsStream();
				});
			}
			catch (UnauthorizedAccessException)
			{
				isUnauthorizedAccess = true;
			}
			if (isUnauthorizedAccess)
			{
				//When, for example, the new track for playing is the same than the current played track.
				return await Task<Stream>.Run(() =>
				{
					return CreateStream(trackId, CreationCollisionOption.GenerateUniqueName);
				});
			}
			return stream;
		}
Beispiel #52
0
        public static async Task <IStorageItem> CreatePathAsync(this StorageFolder folder, string fileLocation, CreationCollisionOption fileCollisionOption, CreationCollisionOption folderCollisionOption)
        {
            if (String.IsNullOrEmpty(fileLocation))
            {
                return(null);
            }

            var separatorIndex = fileLocation.IndexOfAny(new[] { '/', '\\' });

            if (separatorIndex == -1)
            {
                return(await folder.CreateFileAsync(fileLocation, fileCollisionOption));
            }
            else
            {
                var folderName = fileLocation.Substring(0, separatorIndex);
                var subFolder  = await folder.CreateFolderAsync(folderName, folderCollisionOption);

                return(await subFolder.CreatePathAsync(fileLocation.Substring(separatorIndex + 1), fileCollisionOption, folderCollisionOption));
            }
        }
        /// <summary>
        /// Creates File located in Local Storage,
        /// Input file name may include folder paths seperated by "\\".
        /// Example: filename = "Documentation\\Tutorial\\US\\ENG\\version.txt"
        /// </summary>
        /// <param name="filename">File name to create (with full path).</param>
        /// <param name="creationCollisionOption">Option to create.</param>
        /// <param name="rootFolder">Parental folder.</param>
        /// <returns>Created file.</returns>
        public async Task<StorageFile> CreateFileAsync(string filename,
                                                       CreationCollisionOption creationCollisionOption = CreationCollisionOption.FailIfExists,
                                                       StorageFolder rootFolder = null)
        {
            if (string.IsNullOrEmpty(filename) || string.IsNullOrEmpty(Path.GetFileName(filename)))
            {
                return null;
            }

            var semaphore = GetSemaphore(filename);
            await semaphore.WaitAsync();

            try
            {
                rootFolder = rootFolder ?? AntaresBaseFolder.Instance.RoamingFolder;
                return await rootFolder.CreateFileAsync(NormalizePath(filename), creationCollisionOption);
            }
            catch(Exception ex)
            {
                LogManager.Instance.LogException(ex.ToString());
                return null;
            }
            finally
            {
                semaphore.Release();
            }
        }
Beispiel #54
0
 /// <inheritdoc />
 public IFile CreateFile(string desiredName, CreationCollisionOption option) => _folder.CreateFile(desiredName, option);
 public async Task<StorageFile> CreateFileAsync(byte[] bytes, string name, CreationCollisionOption options = CreationCollisionOption.OpenIfExists)
 {
     var file = await CreateFileAsync(name, options);
     await file.TryWriteBytesAsync(bytes);
     return file;
 }
Beispiel #56
0
 /// <inheritdoc />
 public IFolder CreateFolder(string desiredName, CreationCollisionOption option) => _folder.CreateFolder(desiredName, option);
Beispiel #57
0
    private static async Task <StorageFile> AsyncCreateFileAtPath(string path, string name, CreationCollisionOption collisionOption)
    {
        StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(path);

        StorageFolder storageFolder2 = storageFolder;

        return(await storageFolder2.CreateFileAsync(name, collisionOption));
    }
        /// <summary>
        /// Creates a subfolder in this folder
        /// </summary>
        /// <param name="desiredName">The name of the folder to create</param>
        /// <param name="option">Specifies how to behave if the specified folder already exists</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The newly created folder</returns>
        public async Task<IFolder> CreateFolderAsync(string desiredName, CreationCollisionOption option, CancellationToken cancellationToken)
        {
            Requires.NotNullOrEmpty(desiredName, "desiredName");
            await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken);
            EnsureExists();
            string nameToUse = desiredName;
            string newPath = System.IO.Path.Combine(Path, nameToUse);
            if (Directory.Exists(newPath))
            {
                if (option == CreationCollisionOption.GenerateUniqueName)
                {
                    for (int num = 2; Directory.Exists(newPath); num++)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        nameToUse = desiredName + " (" + num + ")";
                        newPath = System.IO.Path.Combine(Path, nameToUse);
                    }
                    Directory.CreateDirectory(newPath);
                }
                else if (option == CreationCollisionOption.ReplaceExisting)
                {
                    Directory.Delete(newPath, true);
                    Directory.CreateDirectory(newPath);
                }
                else if (option == CreationCollisionOption.FailIfExists)
                {
                    throw new IOException("Directory already exists: " + newPath);
                }
                else if (option == CreationCollisionOption.OpenIfExists)
                {
                    //	No operation
                }
                else
                {
                    throw new ArgumentException("Unrecognized CreationCollisionOption: " + option);
                }
            }
            else
            {
                Directory.CreateDirectory(newPath);
            }

            var ret = new FileSystemFolder(newPath, true);
            return ret;
        }
        private static async Task<Stream> OpenStreamForWriteAsyncCore(this IStorageFolder rootDirectory, String relativePath,
                                                                      CreationCollisionOption creationCollisionOption)
        {
            Contract.Requires(rootDirectory != null);
            Contract.Requires(!String.IsNullOrWhiteSpace(relativePath));

            Contract.Requires(creationCollisionOption == CreationCollisionOption.FailIfExists
                                    || creationCollisionOption == CreationCollisionOption.GenerateUniqueName
                                    || creationCollisionOption == CreationCollisionOption.OpenIfExists
                                    || creationCollisionOption == CreationCollisionOption.ReplaceExisting,
                              "The specified creationCollisionOption has a value that is not a value we considered when devising the"
                            + " policy about Append-On-OpenIfExists used in this method. Apparently a new enum value was added to the"
                            + " CreationCollisionOption type and we need to make sure that the policy still makes sense.");

            Contract.Ensures(Contract.Result<Task<Stream>>() != null);
            Contract.EndContractBlock();

            try
            {
                // Open file and set up default options for opening it:

                IStorageFile windowsRuntimeFile = await rootDirectory.CreateFileAsync(relativePath, creationCollisionOption)
                                                                     .AsTask().ConfigureAwait(continueOnCapturedContext: false);
                Int64 offset = 0;

                // If the specified creationCollisionOption was OpenIfExists, then we will try to APPEND, otherwise we will OVERWRITE:

                if (creationCollisionOption == CreationCollisionOption.OpenIfExists)
                {
                    BasicProperties fileProperties = await windowsRuntimeFile.GetBasicPropertiesAsync()
                                                           .AsTask().ConfigureAwait(continueOnCapturedContext: false);
                    UInt64 fileSize = fileProperties.Size;

                    Debug.Assert(fileSize <= Int64.MaxValue, ".NET streams assume that file sizes are not larger than Int64.MaxValue,"
                                                              + " so we are not supporting the situation where this is not the case.");
                    offset = checked((Int64)fileSize);
                }

                // Now open a file with the correct options:

                Stream managedStream = await OpenStreamForWriteAsyncCore(windowsRuntimeFile, offset).ConfigureAwait(continueOnCapturedContext: false);
                return managedStream;
            }
            catch (Exception ex)
            {
                // From this API, managed dev expect IO exceptions for "something wrong":
                WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw();
                return null;
            }
        }
Beispiel #60
0
 private static async Task <StorageFile> AsyncCreateFile(StorageFolder folder, string name, CreationCollisionOption collisionOption)
 {
     return(await folder.CreateFileAsync(name, collisionOption));
 }