当前位置: 首页>>代码示例>>C#>>正文


C# StorageFile.OpenStreamForWriteAsync方法代码示例

本文整理汇总了C#中Windows.Storage.StorageFile.OpenStreamForWriteAsync方法的典型用法代码示例。如果您正苦于以下问题:C# StorageFile.OpenStreamForWriteAsync方法的具体用法?C# StorageFile.OpenStreamForWriteAsync怎么用?C# StorageFile.OpenStreamForWriteAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Windows.Storage.StorageFile的用法示例。


在下文中一共展示了StorageFile.OpenStreamForWriteAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: WriteDataToFileAsync

 public async Task WriteDataToFileAsync(StorageFile file, byte[] data)
 {
     using (var s = await file.OpenStreamForWriteAsync())
     {
         await s.WriteAsync(data, 0, data.Length);
     }
 }
开发者ID:tgptom,项目名称:aerogear-cordova-otp,代码行数:7,代码来源:Repository.cs

示例2: WriteTextIntoFileAsync

		public static async Task<bool> WriteTextIntoFileAsync(string text, StorageFile file)
		{
			try
			{
				if (file != null)
				{
					using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false))
					{
						using (var writer = new StreamWriter(fileStream))
						{
							fileStream.SetLength(0); // avoid leaving crap at the end if overwriting a file that was longer
							fileStream.Seek(0, SeekOrigin.Begin);
							await writer.WriteAsync(text).ConfigureAwait(false);
							await fileStream.FlushAsync();
							await writer.FlushAsync();
							return true;
						}
					}
				}
			}
			catch (Exception ex)
			{
				await Logger.AddAsync(ex.ToString(), Logger.FileErrorLogFilename).ConfigureAwait(false);
			}
			return false;
		}
开发者ID:lolluslollus,项目名称:UniFiler10,代码行数:26,代码来源:DocumentExtensions.cs

示例3: Download

        private async Task Download(string url,StorageFile file,bool cover)
        {
            var http = new HttpClient();
            byte[] response = { };
            string betterUrl = url;
            if(cover)
            {
                var pos = betterUrl.IndexOf(".jpg");
                if (pos != -1)
                    betterUrl = betterUrl.Insert(pos, "l");
            }

            //get bytes
            try
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(betterUrl));
            }
            catch (Exception)
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(url));
            }

            var fs = await file.OpenStreamForWriteAsync(); //get stream
            var writer = new DataWriter(fs.AsOutputStream());

            writer.WriteBytes(response); //write
            await writer.StoreAsync();
            await writer.FlushAsync();

            writer.Dispose();
        }
开发者ID:Mordonus,项目名称:MALClient,代码行数:31,代码来源:ImageDownloaderService.cs

示例4: SaveConfigurationsToFileAsync

 public async Task SaveConfigurationsToFileAsync(IEnumerable<ServiceConfiguration> configurations, StorageFile storageFile)
 {
     string data = await _serializer.SerializeAsync(configurations.ToArray());
     using (Stream stream = await storageFile.OpenStreamForWriteAsync())
     {
         await _zipper.WriteCompressedDataToStreamAsync(stream, data);
     }
 }
开发者ID:johanclasson,项目名称:Rester,代码行数:8,代码来源:ConfigurationStore.cs

示例5: RendererImageAsync

		public static Task RendererImageAsync(StorageFile file, SvgImageRendererSettings settings, CancellationToken token)
		{
			return ThreadPool.RunAsync(_ =>
			{
				using (var stream = file.OpenStreamForWriteAsync().GetAwaiter().GetResult())
				{
					RendererImage(stream, settings);
				}
			}).AsTask(token);
		}
开发者ID:lallous,项目名称:SvgForXaml,代码行数:10,代码来源:SvgImageRenderer.cs

示例6: GetStreamBasedOnDirection

 protected static async Task<Stream> GetStreamBasedOnDirection(StorageFile file, TransferDirection direction)
 {
     switch (direction)
     {
         case TransferDirection.Up:
             return await file.OpenStreamForReadAsync();
         case TransferDirection.Down:
             return await file.OpenStreamForWriteAsync();
     }
     return null;
 }
开发者ID:ProMcTagonist,项目名称:OneTox,代码行数:11,代码来源:OneFileTransferModel.cs

示例7: SetTagsSharp

        public static async void SetTagsSharp(TagsPackage tagsPck, StorageFile file, int nRetries = 5) //Using TagLibSharp
        {
            try
            {
                var fileStream = await file.OpenStreamForWriteAsync();

                var tagFile = TagLib.File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream));

                tagFile.Tag.Title = tagsPck.title;
                tagFile.Tag.Performers = new[] {tagsPck.artist};
                tagFile.Tag.Album = tagsPck.album;
                if (tagsPck.ThumbSource != null)
                {

                    TagLib.Id3v2.AttachedPictureFrame pic = new TagLib.Id3v2.AttachedPictureFrame
                    {
                        TextEncoding = StringType.Latin1,
                        Type = PictureType.FrontCover
                    };
                    var uri = new Uri(tagsPck.ThumbSource);         
                    if (!uri.IsFile)
                    {
                        var rass = RandomAccessStreamReference.CreateFromUri(uri);
                        IRandomAccessStream stream = await rass.OpenReadAsync();
                        pic.Data = ByteVector.FromStream(stream.AsStream());
                        pic.MimeType = "image/jpeg";
                        stream.Dispose();
                    }
                    else
                    {
                        StorageFile thumb = await StorageFile.GetFileFromPathAsync(tagsPck.ThumbSource);
                        var thumbStream = await thumb.OpenStreamForReadAsync();
                        pic.Data = ByteVector.FromFile(new StreamFileAbstraction("Cover", thumbStream, thumbStream));
                        pic.MimeType = thumb.Name.Contains(".png") ? "image/png" : "image/jpeg";
                        thumbStream.Dispose();
                    }

                    tagFile.Tag.Pictures = new IPicture[1] {pic};
                    
                }

                tagFile.Save();
                fileStream.Dispose();                          
            }
            catch (Exception exc)
            {
                Debug.WriteLine("TagsProcessing : " + exc.Message);
                await Task.Delay(TimeSpan.FromSeconds(5));
                if (nRetries >= 0)
                    SetTagsSharp(tagsPck, file, nRetries - 1);
            }
        }
开发者ID:Mordonus,项目名称:YoutubeDownloader,代码行数:52,代码来源:TagProcessing.cs

示例8: write

 private async void write()
 {
     try
     {
         file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename,
             CreationCollisionOption.ReplaceExisting);
         using (Stream stream = await file.OpenStreamForWriteAsync())
         {
             new DataContractJsonSerializer(typeof(ObservableCollection<Music>))
                 .WriteObject(stream, collection);
         }
     }
     catch
     {
     }
 }
开发者ID:RoguePlanetoid,项目名称:Windows-10-Universal-Windows-Platform,代码行数:16,代码来源:Library.cs

示例9: DownloadFileToStorageAsync

        public async Task<StorageFile> DownloadFileToStorageAsync(string filename, Uri source, StorageFile outputFile)
        {
            using (HttpClient client = new HttpClient())
            {
                byte[] buffer = await client.GetByteArrayAsync(source); // Download file
                filename = filename != "/" ? filename : Guid.NewGuid().ToString();
                outputFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                // TODO: Autodelete guids after eg. 2 weeks
                using (Stream stream = await outputFile.OpenStreamForWriteAsync())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }

            return outputFile;
        }
开发者ID:chenjianwp,项目名称:UWP_ToolKit_CommonLibrary,代码行数:17,代码来源:GifFileHandler.cs

示例10: WriteMenuCardToFileAsync

 public async Task WriteMenuCardToFileAsync(MenuCard menuCard, StorageFile storageFile)
 {
     var menuCardData = new MenuCardData(menuCard);
     var knownTypes = new Type[]
   {
     typeof(MenuItemData)
   };
     var cardStream = new MemoryStream();
     var serializer = new DataContractSerializer(typeof(MenuCardData), knownTypes);
     serializer.WriteObject(cardStream, menuCardData);
     using (Stream fileStream = await storageFile.OpenStreamForWriteAsync())
     {
         cardStream.Seek(0, SeekOrigin.Begin);
         await cardStream.CopyToAsync(fileStream);
         await fileStream.FlushAsync();
     }
 }
开发者ID:xxy1991,项目名称:cozy,代码行数:17,代码来源:MenuCardStorage.cs

示例11: writePackageAsync

        public async Task<bool> writePackageAsync(StorageFile file, Deck outDeck)
        {
            this.deck = outDeck;
            StorageFolder tmpFolder = ApplicationData.Current.TemporaryFolder;
            //create a MemoryStream to build ZipArchive in Memory
            using (MemoryStream zipStream = new MemoryStream())
            {

                //Create ZipArchive using MemoryStream
                using (ZipArchive archive = new ZipArchive(zipStream,ZipArchiveMode.Create,true)) { //leave zipstream open so we can copy from it later.
                    //Write File(s) to ZipArchive as entries
                    //for every image referenced by a card, we'll need to copy them over
                    String[] segments;
                    ZipArchiveEntry en;
                    foreach (Card c in this.deck.cards)
                    {
                        if (c.hasSideAImage())
                        {
                            segments = c.sideAImage.UriSource.Segments;
                            StorageFile inFile = await tmpFolder.GetFileAsync(segments[segments.Count() - 1]); //to be copied

                            using (Stream s = await inFile.OpenStreamForReadAsync()) //incoming stream
                            {
                                en = archive.CreateEntry(segments[segments.Count() - 1]);
                                using (Stream sout = en.Open()) //outgoing stream. Can't use en.Open() directly because it won't get properly disposed.
                                {
                                    await s.CopyToAsync(sout);
                                }
                            }
                        }
                        if (c.hasSideBImage())
                        {
                            segments = c.sideBImage.UriSource.Segments;
                            StorageFile inFile = await tmpFolder.GetFileAsync(segments[segments.Count() - 1]); //to be copied

                            using (Stream s = await inFile.OpenStreamForReadAsync()) //incoming stream
                            {
                                en = archive.CreateEntry(segments[segments.Count() - 1]);
                                using (Stream sout = en.Open()) //outgoing stream. Can't use en.Open() directly because it won't get properly disposed.
                                {
                                    await s.CopyToAsync(sout);
                                }
                            }
                        }

                    }
                    //Then we write the deck description file
                    deckToXml();
                    en = archive.CreateEntry("deckdescription.xml");
                    using (StreamWriter sw = new StreamWriter(en.Open()))
                    {
                        sw.Write(this.deckXml);
                    }

                }
            //Copy MemoryStream (entire Zip Archive) to file specified
                zipStream.Position = 0;
                using (Stream s = await file.OpenStreamForWriteAsync())
                {
                    zipStream.CopyTo(s);
                }
            }

            return true;
        }
开发者ID:ryansloan,项目名称:QuizCards,代码行数:65,代码来源:DeckPackageProcessor.cs

示例12: Save2Async

		private async Task<bool> Save2Async(StorageFile file = null)
		{
			//for (int i = 0; i < 100000000; i++) //wait a few seconds, for testing
			//{
			//    String aaa = i.ToString();
			//}
			await Logger.AddAsync("MetaBriefcase about to save", Logger.FileErrorLogFilename, Logger.Severity.Info).ConfigureAwait(false);
			bool result = false;

			// save xml properties
			try
			{
				_localDataSemaphore.WaitOne();

				if (file == null)
				{
					file = await GetDirectory()
						.TryGetItemAsync(FILENAME).AsTask().ConfigureAwait(false) as StorageFile;
				}

				string savedData = string.Empty;
				if (file != null)
				{
					using (var localFileContent = await file.OpenStreamForReadAsync().ConfigureAwait(false))
					{
						using (StreamReader streamReader = new StreamReader(localFileContent))
						{
							savedData = streamReader.ReadToEnd();
						}
					}
				}

				using (var memoryStream = new MemoryStream())
				{
					var serializer = new DataContractSerializer(typeof(MetaBriefcase));
					serializer.WriteObject(memoryStream, this);

					string currentMetaBriefcase = string.Empty;
					memoryStream.Seek(0, SeekOrigin.Begin);
					using (StreamReader streamReader = new StreamReader(memoryStream))
					{
						currentMetaBriefcase = streamReader.ReadToEnd();

						if (!currentMetaBriefcase.Trim().Equals(savedData.Trim()))
						{
							if (file == null)
							{
								file = await GetDirectory()
									.CreateFileAsync(FILENAME, CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false);
							}

							using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false))
							{
								fileStream.SetLength(0); // avoid leaving crap at the end if overwriting a file that was longer
								memoryStream.Seek(0, SeekOrigin.Begin);
								await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
								await memoryStream.FlushAsync().ConfigureAwait(false);
								await fileStream.FlushAsync().ConfigureAwait(false);
							}
						}
					}
				}
				Debug.WriteLine("ended method MetaBriefcase.SaveAsync()");
				result = true;
			}
			catch (Exception ex)
			{
				Logger.Add_TPL(ex.ToString(), Logger.FileErrorLogFilename);
			}
			finally
			{
				// save non-xml properties
				result = result & RegistryAccess.TrySetValue(ConstantData.REG_MBC_IS_ELEVATED, IsElevated.ToString());
				SemaphoreExtensions.TryRelease(_localDataSemaphore);
			}

			return result;
		}
开发者ID:lolluslollus,项目名称:UniFiler10,代码行数:78,代码来源:MetaBriefcase.cs

示例13: RemoveFileFromZipHelper

        private static async Task RemoveFileFromZipHelper(StorageFile zipFile, StorageFile file)
        {
            if (
                    zipFile == null ||
                    !Path.GetExtension(zipFile.Name)
                        .Equals(".epub", StringComparison.OrdinalIgnoreCase)
                    )
            {
                throw new ArgumentException("Invalid argument...");
            }

            Stream zipMemoryStream = await zipFile.OpenStreamForWriteAsync();

            using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Update))
            {
                ZipArchiveEntry currentEntry = null;
                String fileName = "OEBPS/" + file.Name;

                // Unzip compressed file iteratively.
                foreach (ZipArchiveEntry entry in zipArchive.Entries)
                {
                    if (entry.FullName == fileName)
                    {
                        currentEntry = entry;
                    }
                }
                
                if (currentEntry != null) {
                    currentEntry.Delete();
                }
                zipArchive.Dispose();
            }
            zipMemoryStream.Dispose();
        }
开发者ID:rudenoise,项目名称:winFileAssoc,代码行数:34,代码来源:ZipHelper.cs

示例14: writeBinaryASync

 public static async Task writeBinaryASync(object value, StorageFile file)
 {
     var s = await file.OpenStreamForWriteAsync();
     writeBinary(value, s);
 }
开发者ID:jijixi,项目名称:PlistCS,代码行数:5,代码来源:Plist.cs

示例15: HttpGetFileAsync

        public static async Task HttpGetFileAsync(string url, StorageFile targetFile, Action<int, int> progressAction, CancellationToken token = new CancellationToken())
        {
            using (var httpFilter = new HUwpHttpFilter())
            using (var client = new HttpClient(httpFilter))
            using (var response = await client.SendRequestAsync(new HttpRequestMessage(HttpMethod.Get, new Uri(url)), HttpCompletionOption.ResponseHeadersRead))
            {
                response.EnsureSuccessStatusCode();

                using (var resStream = await response.Content.ReadAsInputStreamAsync())
                using (var classicResStream = resStream.AsStreamForRead())
                {
                    var resContentLength = response.Content.Headers.ContentLength;

                    using (var fileStream = await targetFile.OpenStreamForWriteAsync())
                    {
                        var buf = new byte[1000000];
                        var offset = 0;
                        fileStream.Seek(0, SeekOrigin.Begin);

                        while (true)
                        {
                            int read = await classicResStream.ReadAsync(buf, 0, buf.Length, token);
                            progressAction.Invoke(offset, (int)resContentLength);

                            if (read <= 0)
                                break;

                            await fileStream.WriteAsync(buf, 0, read, token);
                            offset += read;
                        }

                        progressAction.Invoke((int)resContentLength, (int)resContentLength);
                    }
                }
            }
        }
开发者ID:HyundongHwang,项目名称:HUwpBaseLib,代码行数:36,代码来源:HublUtils.cs


注:本文中的Windows.Storage.StorageFile.OpenStreamForWriteAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。