internal async static Task WriteBytesAsync(IStorageFile storageFile, byte[] bytes) { using (Stream stream = await storageFile.OpenStreamForWriteAsync()) { await stream.WriteAsync(bytes, 0, bytes.Length); } }
public async Task CopyAndReplaceAsync(IStorageFile fileToReplace) { using (var targetStream = await fileToReplace.OpenStreamForWriteAsync()) { await this.SftpDataSource.SftpClient.DownloadFileAsync(this.Path, targetStream); } }
private static async Task WriteTextTaskAsync(IStorageFile file, string contents, bool append, UwpUnicodeEncoding?encoding = null) { if (file is null) { throw new ArgumentNullException(nameof(file)); } Encoding systemEncoding; if (encoding == null) { systemEncoding = await GetEncodingFromFileAsync(file); } else { systemEncoding = UwpEncodingToSystemEncoding(encoding.Value); } using var fileStream = await file.OpenStreamForWriteAsync(); if (append) { fileStream.Seek(0, SeekOrigin.End); } else { // reset file content, as UWP does fileStream.SetLength(0); } using StreamWriter streamWriter = new StreamWriter(fileStream, systemEncoding); await streamWriter.WriteAsync(contents); }
private async Task SaveFile(IStorageFile arg) { using (var reader = new StreamWriter(await arg.OpenStreamForWriteAsync())) { await reader.WriteAsync(source); } }
internal async static Task WriteTextAsync(IStorageFile storageFile, string text) { using (Stream stream = await storageFile.OpenStreamForWriteAsync()) { byte[] content = Encoding.UTF8.GetBytes(text); await stream.WriteAsync(content, 0, content.Length); } }
public static async Task SerializeAsync <T>(IStorageFile file, T o) { var seri = new XmlSerializer(typeof(DataContainer)); using (var stream = await file.OpenStreamForWriteAsync()) { seri.Serialize(stream, o); } }
private async Task InitializeStorageFile(IStorageFile file) { string message = "Short message!"; using (var stream = await file.OpenStreamForWriteAsync()) { stream.Write(Encoding.UTF8.GetBytes(message), 0, message.Length); } }
private static async Task WriteJsonToFileAsync(this IStorageFile file, Type objectType, object item) { var serializer = JsonSerializer.Create(serialisationSettings); using (var stream = await file.OpenStreamForWriteAsync()) using (var writer = new StreamWriter(stream)) using (var jsonWriter = new JsonTextWriter(writer)) serializer.Serialize(jsonWriter, item, objectType); }
public static async Task SaveToFile(this ZipArchiveEntry entry, IStorageFile file) { Stream newFileStream = await file.OpenStreamForWriteAsync(); Stream fileData = entry.Open(); var data = new byte[entry.Length]; await fileData.ReadAsync(data, 0, data.Length); newFileStream.Write(data, 0, data.Length); await newFileStream.FlushAsync(); }
/// <summary>Writes information to XML.</summary> /// <param name="newFile">The new file.</param> /// <param name="info">The information.</param> public static async void WriteToXml(IStorageFile newFile, HighScoreRecord info) { var serializer = new XmlSerializer(typeof(HighScoreRecord)); var writeStream = await newFile.OpenStreamForWriteAsync(); serializer.Serialize(writeStream, info); writeStream.Close(); }
public static void WriteStreamToFile(IStorageFile file, Stream stream) { Task.Run(async() => { using (var ostream = await file.OpenStreamForWriteAsync()) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(ostream); } }); }
private static async Task WriteBytesTaskAsync(IStorageFile file, byte[] buffer, int index, int count) { if (file is null) { throw new ArgumentNullException(nameof(file)); } using var fs = await file.OpenStreamForWriteAsync(); await fs.WriteAsync(buffer, 0, buffer.Length); }
/// <summary> /// Saves instance of RenderTargetBitmap to specified file. /// </summary> public static async Task SaveToFileAsync(this RenderTargetBitmap image, IStorageFile file) { using (var stream = await file.OpenStreamForWriteAsync()) { var encoder = await BitmapEncoder.CreateAsync( BitmapEncoder.JpegEncoderId, stream.AsRandomAccessStream()); var pixels = await image.GetPixelsAsync(); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, DefaultDPI, DefaultDPI, pixels.ToArray()); await encoder.FlushAsync(); } }
public override IAsyncAction CopyAndReplaceAsync(IStorageFile fileToReplace) { return(AsyncInfo.Run(async(cancellationToken) => { using (var inStream = await this.OpenStreamForReadAsync()) using (var outStream = await fileToReplace.OpenStreamForWriteAsync()) { await inStream.CopyToAsync(outStream); await outStream.FlushAsync(); } })); }
public async Task SaveToFileAsync <TItem>(IStorageFile file, TItem item) { var stm = new MemoryStream(); GetCoreSerializer <TItem>().WriteObject(stm, item); stm.Position = 0; using (var tstm = await file.OpenStreamForWriteAsync()) { await stm.CopyToAsync(tstm); } }
public async Task <TItem> LoadFromFileAsync <TItem>(IStorageFile file) { var stm = new MemoryStream(); using (var tstm = await file.OpenStreamForWriteAsync()) { await tstm.CopyToAsync(stm); } stm.Position = 0; return((TItem)GetCoreSerializer <TItem>().ReadObject(stm)); }
private static async Task WriteBytesTaskAsync(IStorageFile file, byte[] buffer, CancellationToken cancellationToken) { if (file is null) { throw new ArgumentNullException(nameof(file)); } using var fs = await file.OpenStreamForWriteAsync(); await fs.WriteAsync(buffer, 0, buffer.Length, cancellationToken); await fs.FlushAsync(); }
public override IAsyncAction MoveAndReplaceAsync(IStorageFile fileToReplace) { return(AsyncInfo.Run(async(cancellationToken) => { using (var inStream = await this.OpenStreamForReadAsync()) using (var outStream = await fileToReplace.OpenStreamForWriteAsync()) { await inStream.CopyToAsync(outStream); await outStream.FlushAsync(); } // Move unsupported, copy but do not delete original })); }
/// <summary> /// Saves instance of WriteableBitmap to specified file. /// </summary> public static async Task SaveToFileAsync(this WriteableBitmap image, IStorageFile file) { using (var stream = await file.OpenStreamForWriteAsync()) { var encoder = await BitmapEncoder.CreateAsync( BitmapEncoder.JpegEncoderId, stream.AsRandomAccessStream()); var pixelStream = image.PixelBuffer.AsStream(); var pixels = new byte[image.PixelBuffer.Length]; await pixelStream.ReadAsync(pixels, 0, pixels.Length); encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)image.PixelWidth, (uint)image.PixelHeight, DefaultDPI, DefaultDPI, pixels); await encoder.FlushAsync(); } }
private async Task <Stream> GetFileStreamWriteAsync(string filePath) { // TODO: create folders/file if not exists StorageFolder folder = Package.Current.InstalledLocation; foreach (string subfolder in Path.GetDirectoryName(filePath).Split(Separators, StringSplitOptions.RemoveEmptyEntries)) { folder = await folder.GetFolderAsync(subfolder); } IStorageFile file = await folder.GetFileAsync(Path.GetFileName(filePath)); return(await file.OpenStreamForWriteAsync()); }
private async void writeToXml(IStorageFile newFile, Score score) { var serializer = new XmlSerializer(typeof(ScoreBoard)); var writeStream = await newFile.OpenStreamForWriteAsync(); var board = new ScoreBoard(); using (writeStream) { board.Add(score); serializer.Serialize(writeStream, board); } writeStream.Dispose(); }
public async Task <string> SaveBase64Async(string fileName, string sreamFile) { byte[] fileBytes = System.Convert.FromBase64String(sreamFile); StorageFolder localFolder = await GetStorageDirectory(); IStorageFile file = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (var stream = await file.OpenStreamForWriteAsync()) { await stream.WriteAsync(fileBytes, 0, fileBytes.Length); } return(file.Path.ToString()); }
public async Task <bool> WriteFile(IStorageFile file, Stream data) { using (var fileStream = await file.OpenStreamForWriteAsync()) { const int BUFFER_SIZE = 1024; byte[] buf = new byte[BUFFER_SIZE]; int bytesread = 0; while ((bytesread = await data.ReadAsync(buf, 0, BUFFER_SIZE)) > 0) { await fileStream.WriteAsync(buf, 0, bytesread); } } return(true); }
private static async Task SaveTransmissionToFileAsync(Transmission transmission, IStorageFile file) { try { using (Stream stream = await file.OpenStreamForWriteAsync().ConfigureAwait(false)) { await StorageTransmission.SaveAsync(transmission, stream).ConfigureAwait(false); } } catch (UnauthorizedAccessException) { string message = string.Format("Failed to save transmission to file. UnauthorizedAccessException. File path: {0}, FileName: {1}", file.Path, file.Name); CoreEventSource.Log.LogVerbose(message); throw; } }
internal static async Task WriteTextTaskAsync(IStorageFile file, string contents, bool append, bool recognizeEncoding, CancellationToken cancellationToken, UwpUnicodeEncoding?encoding = null) { if (file is null) { throw new ArgumentNullException(nameof(file)); } Encoding systemEncoding; if (encoding == null) { if (recognizeEncoding) { systemEncoding = await GetEncodingFromFileAsync(file); } else { systemEncoding = Encoding.Default; } } else { systemEncoding = UwpEncodingToSystemEncoding(encoding.Value); } using var fileStream = await file.OpenStreamForWriteAsync(); if (append) { fileStream.Seek(0, SeekOrigin.End); } else { // reset file content, as UWP does fileStream.SetLength(0); } using StreamWriter streamWriter = new StreamWriter(fileStream, systemEncoding); // Configure autoflush, for it seems FlushAsync does not flush properly // on .NET 6 preview 1 (WebAssembly). Failure in runtime tests otherwise. streamWriter.AutoFlush = true; await streamWriter.WriteAsync(contents); await streamWriter.FlushAsync(); }
public async static Task WriteData(string folderName, string fileName, byte[] content) { IStorageFolder rootFolder = ApplicationData.Current.LocalFolder; if (folderName != string.Empty) { rootFolder = await rootFolder.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists); } IStorageFile file = await rootFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (var s = await file.OpenStreamForWriteAsync()) { s.Write(content, 0, content.Length); } }
/// <summary> /// Writes text to the specified file using the specified character encoding. /// </summary> /// <param name="file">The file that the text is written to.</param> /// <param name="contents">The text to write.</param> /// <param name="encoding">The character encoding of the file.</param> /// <returns>No object or value is returned when this method completes.</returns> public static Task WriteTextAsync(IStorageFile file, string contents, UnicodeEncoding encoding) { #if __ANDROID__ || __UNIFIED__ || WIN32 || TIZEN return(PathIO.WriteTextAsync(file.Path, contents, encoding)); #elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE_81 return(Windows.Storage.FileIO.WriteTextAsync((Windows.Storage.StorageFile)((StorageFile)file), contents, (Windows.Storage.Streams.UnicodeEncoding)((int)encoding)).AsTask()); #elif WINDOWS_PHONE return(Task.Run(async() => { Stream s = await file.OpenStreamForWriteAsync(); using (StreamWriter sw = new StreamWriter(s, UnicodeEncodingHelper.EncodingFromUnicodeEncoding(encoding))) sw.Write(contents); })); #else throw new PlatformNotSupportedException(); #endif }
private static async Task WriteSongToCache(IStorageFile file, byte[] data) { using (var stream = await file.OpenStreamForWriteAsync()) { var chunks = data.Length / DefaultBufferSize; if (data.Length % DefaultBufferSize > 0) { await stream.WriteAsync(data, chunks *DefaultBufferSize, data.Length - (chunks *DefaultBufferSize)); } for (int i = chunks - 1; i >= 0; i--) { await stream.WriteAsync(data, i *DefaultBufferSize, DefaultBufferSize); } } }
public async Task WriteResponseStreamToFileAsync(IStorageFile storageFile, bool append, CancellationToken cancellationToken) { Stream outputStream = await storageFile.OpenStreamForWriteAsync().ConfigureAwait(false); if (append) { outputStream.Seek(0, SeekOrigin.End); } try { long current = 0; var inputStream = this.ResponseStream; byte[] buffer = new byte[S3Constants.DefaultBufferSize]; int bytesRead = 0; long totalIncrementTransferred = 0; while ((bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length) .ConfigureAwait(continueOnCapturedContext: false)) > 0) { cancellationToken.ThrowIfCancellationRequested(); await outputStream.WriteAsync(buffer, 0, bytesRead) .ConfigureAwait(continueOnCapturedContext: false); current += bytesRead; totalIncrementTransferred += bytesRead; if (totalIncrementTransferred >= AWSSDKUtils.DefaultProgressUpdateInterval || current == this.ContentLength) { this.OnRaiseProgressEvent(storageFile.Path, bytesRead, current, this.ContentLength); totalIncrementTransferred = 0; } } ValidateWrittenStreamSize(current); } finally { if (outputStream != null) { outputStream.Dispose(); } } }
/// <summary> /// Compress folder async to file. /// </summary> /// <param name="folder">Folder to compress. Only folder content will be zipped.</param> /// <param name="file">File to compress.</param> /// <returns></returns> public async Task <bool> CompressAsync(IStorageFolder folder, IStorageFile file) { if (folder == null || file == null) { Logger.WriteLine("Folder or file not valid."); return(false); } using (var fs = await file.OpenStreamForWriteAsync()) { using (var zipArchive = new ZipArchive(fs, ZipArchiveMode.Update)) { await CompressRecursiveAsync(zipArchive, folder, ""); } } return(true); }
public async Task WriteResponseStreamToFileAsync(IStorageFile storageFile, bool append, CancellationToken cancellationToken) { Stream outputStream = await storageFile.OpenStreamForWriteAsync().ConfigureAwait(false); if (append) { outputStream.Seek(0, SeekOrigin.End); } try { long current = 0; var inputStream = this.ResponseStream; byte[] buffer = new byte[S3Constants.DefaultBufferSize]; int bytesRead = 0; long totalIncrementTransferred = 0; while ((bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length) .ConfigureAwait(continueOnCapturedContext: false)) > 0) { cancellationToken.ThrowIfCancellationRequested(); await outputStream.WriteAsync(buffer, 0, bytesRead) .ConfigureAwait(continueOnCapturedContext: false); current += bytesRead; totalIncrementTransferred += bytesRead; if (totalIncrementTransferred >= AWSSDKUtils.DefaultProgressUpdateInterval || current == this.ContentLength) { this.OnRaiseProgressEvent(storageFile.Path, bytesRead, current, this.ContentLength); totalIncrementTransferred = 0; } } ValidateWrittenStreamSize(current); } finally { if (outputStream!=null) { outputStream.Dispose(); } } }
public async Task SaveImage(string url, IStorageFile outputFile) { try { var response = new HttpResponseMessage(); response = await httpClient.GetAsync(url); var responseStream = await response.Content.ReadAsStreamAsync(); using (var fs = await outputFile.OpenStreamForWriteAsync()) { await responseStream.CopyToAsync(fs); } response.Dispose(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } }
private async Task Save(List <Data> data) { IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; IStorageFolder storageFolder = await applicationFolder.CreateFolderAsync("data", CreationCollisionOption.OpenIfExists); string fileName = "data.json"; IStorageFile storageFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists); using (Stream stream = await storageFile.OpenStreamForWriteAsync()) using (var sw = new StreamWriter(stream)) using (JsonWriter jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(jw, data); await stream.FlushAsync(); } }
public async Task <IStorageFile> DownloadRulesFileAsync2() { IStorageFile file = await this.rulesFile; AppLog.Instance.Debug("Unable to find local rules PDF for {0}. Downloading from {1}", this.localFileName, this.RulesUri); // The file wasn't found so let's download the file. using (HttpClient client = new HttpClient()) { Stream rulesFileStream = await client.GetStreamAsync(this.RulesUri); using (var storageFileStream = await file.OpenStreamForWriteAsync()) { await rulesFileStream.CopyToAsync(storageFileStream); AppLog.Instance.Debug("Finished downloading rules file."); } } return(file); }
/// <summary> /// Appends lines of text to the specified file using the specified character encoding. /// </summary> /// <param name="file">The file that the lines are appended to.</param> /// <param name="lines">The list of text strings to append as lines.</param> /// <param name="encoding">The character encoding of the file.</param> /// <returns>No object or value is returned when this method completes.</returns> public static Task AppendLinesAsync(IStorageFile file, IEnumerable<string> lines, UnicodeEncoding encoding) { #if __ANDROID__ || __IOS__ || __TVOS__ || WIN32 || TIZEN return PathIO.AppendLinesAsync(file.Path, lines, encoding); #elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE_81 return Windows.Storage.FileIO.AppendLinesAsync((Windows.Storage.StorageFile)((StorageFile)file), lines, (Windows.Storage.Streams.UnicodeEncoding)((int)encoding)).AsTask(); #elif WINDOWS_PHONE return Task.Run(async () => { Stream s = await file.OpenStreamForWriteAsync(); s.Position = s.Length; using (StreamWriter sw = new StreamWriter(s, UnicodeEncodingHelper.EncodingFromUnicodeEncoding(encoding))) { foreach (string line in lines) { sw.WriteLine(line); } } }); #else throw new PlatformNotSupportedException(); #endif }
/// <summary> /// Updates the id3 tags. WARNING, there needs to be more testing with lower end devices. /// </summary> /// <param name="song">The song.</param> /// <param name="file">The file.</param> private async Task UpdateId3TagsAsync(Song song, IStorageFile file) { using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false)) { File tagFile; try { tagFile = File.Create(new SimpleFileAbstraction(file.Name, fileStream, fileStream)); } catch { // either the download is corrupted or is not an mp3 file return; } var newTags = tagFile.GetTag(TagTypes.Id3v2, true); newTags.Title = song.Name; if (song.Artist.ProviderId != "autc.unknown") { newTags.Performers = song.ArtistName.Split(',').Select(p => p.Trim()).ToArray(); } newTags.Album = song.Album.Name; newTags.AlbumArtists = new[] {song.Album.PrimaryArtist.Name}; if (!string.IsNullOrEmpty(song.Album.Genre)) { newTags.Genres = song.Album.Genre.Split(',').Select(p => p.Trim()).ToArray(); } newTags.Track = (uint) song.TrackNumber; newTags.Comment = "Downloaded with Audiotica - http://audiotica.fm"; try { if (song.Album.HasArtwork) { var albumFilePath = string.Format(AppConstant.ArtworkPath, song.Album.Id); var artworkFile = await StorageHelper.GetFileAsync(albumFilePath).ConfigureAwait(false); using (var artworkStream = await artworkFile.OpenAsync(FileAccess.Read)) { using (var memStream = new MemoryStream()) { await artworkStream.CopyToAsync(memStream); newTags.Pictures = new IPicture[] { new Picture( new ByteVector( memStream.ToArray(), (int) memStream.Length)) }; } } } } catch (UnauthorizedAccessException) { // Should never happen, since we are opening the files in read mode and nothing is locking it. } await Task.Run(() => tagFile.Save()); } }
/// <summary> /// Writes text to the specified file using the specified character encoding. /// </summary> /// <param name="file">The file that the text is written to.</param> /// <param name="contents">The text to write.</param> /// <param name="encoding">The character encoding of the file.</param> /// <returns>No object or value is returned when this method completes.</returns> public static Task WriteTextAsync(IStorageFile file, string contents, UnicodeEncoding encoding) { #if __ANDROID__ || __IOS__ || __TVOS__ || WIN32 || TIZEN return PathIO.WriteTextAsync(file.Path, contents, encoding); #elif WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE_81 return Windows.Storage.FileIO.WriteTextAsync((Windows.Storage.StorageFile)((StorageFile)file), contents, (Windows.Storage.Streams.UnicodeEncoding)((int)encoding)).AsTask(); #elif WINDOWS_PHONE return Task.Run(async () => { Stream s = await file.OpenStreamForWriteAsync(); using (StreamWriter sw = new StreamWriter(s, UnicodeEncodingHelper.EncodingFromUnicodeEncoding(encoding))) sw.Write(contents); }); #else throw new PlatformNotSupportedException(); #endif }