本文整理汇总了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);
}
}
示例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;
}
示例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();
}
示例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);
}
}
示例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);
}
示例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;
}
示例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);
}
}
示例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
{
}
}
示例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;
}
示例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();
}
}
示例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;
}
示例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;
}
示例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();
}
示例14: writeBinaryASync
public static async Task writeBinaryASync(object value, StorageFile file)
{
var s = await file.OpenStreamForWriteAsync();
writeBinary(value, s);
}
示例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);
}
}
}
}