await datawriter.storejs async await缺少geiawaiter定义什么情况

时间都去哪儿了,你为什么不努力
Windows Phone中Stream和Buffer类读写操作(不仅仅是文本文件)
FileIO.ReadTextAsync(file)
FileIO.WriteTextAsync(file)
StreamReader和StreamWriter类
以上都是基于操作的是文本内容的文件,而如果操作图片文件或者其他二进制文件就需要操作文件的Stream和Buffer
操作这种二进制的文件,需要用到DataWriter类和DataReader类,前者用于写入文件信息,各种类型的数据信息都
可以进行写入(包括文本信息),后者用于读取文件内容。
Buffer类写入操作
文件的Buffer操作使用的是IBuffer对象,所以需使用DataWriter类写入相关信息之后再转化为IBuffer对象,然后保存
到文件中。其中相关信息指先写入信息的长度(类型可能是Int32),然后写入具体的信息内容等等,总而言之就是这个
文件组成的各个部分,简言之就是读写规则:需要先写入什么,后写入什么,与之对应的就需要先读取什么,后读取
什么,如果一味的用读取字符串的方式读取,那么就读取不到信息长度,进而就无法读取整个文件,这也是为什么利
用StreamReader.ReadToEnd()无法读取除了文本文件以外的文件的原因。
using(InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
using(DataWriter dataWriter = new DataWriter(memoryStream))
//文件相关信息,根据文件规则进行写入
dataWriter.WriteInt32(size);
dataWriter.WriteString(Content);
IBuffer buffer = dataWriter.DetachBuffer();
await FileIO.WriteBufferAsync(file, buffer);
2. Buffer的读取操作
读取操作就是获取文件的IBuffer对象之后再使用IBuffer对象初始化一个DataReader对象,然后就可以对文件进行读
取操作了。
IBuffer buffer = await FileIO.ReadBufferAsync(file);
using(DataReader dataReader = DataReader.FromBuffer(buffer))
//读取文件相关信息,读取的规则和文件的规则一致
Int32 stringSize = dataReader.ReadInt32();
string fileContent = dataReader.ReadString((uint)stringSize);
3. Stream的写入操作
文件的Stream其实就是文件内容的信息,所以在用Stream来写入文件的数据的时候,直接保存Stream的信息即可,
不需要再调用文件的对象进行保存。
using(StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
using(DataWriter dataWriter = new DataWriter(transaction.Stream))
//文件的相关信息,根据文件的规则写入
dataWriter.WriteInt32(size);
dataWriter.WriteString(content);
transaction.Stream.Size = await dataWriter.StoreAsync();
//保存Stream数据
await transaction.CommitAsync();
4. Stream的读取操作
使用Stream读取文件的内容,需要先调用DataReader类的LoadAsync()方法,将数据加载进来,在调用相关的Read
方法读取文件的内容。而可以注意到之前Buffer读取操作没有调用DataReader的LoadAsync()方法,这是因为它已经
一次性的将数据读取出来了(DataReader.FromBuffer(buffer))。
using(IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
using(DataReader dataReader = new DataReader(readStream))
//读取文件相关信息,根据文件规则读取
await dataReader.LoadAsync(sizeof(Int32));
Int32 stringSize = dataReader.ReadInt32();
await dataReader.LoadAsync((UInt32)stringSize);
string content = dataReader.ReadString((uint)stringSize);
没有更多推荐了,重新想象 Windows 8 Store Apps (63) - 通信: WebSocket - webabcd - 博客园
posts - 615, comments - 10475, trackbacks - 594, articles - 0
重新想象 Windows 8 Store Apps (63) - 通信: WebSocket
作者:介绍重新想象 Windows 8 Store Apps 之&通信
Socket - 与 WebSocket 服务端做 Text 通信
Socket - 与 WebSocket 服务端做 Stream(Binary) 通信
示例WebSocket 的服务端WebServer/WebSocketServer.ashx.cs
* WebSocket 协议的服务端
* 需要在 iis 启用 WebSocket 协议:控制面板 -& 程序和功能 -& 启用或关闭 Windows 功能 -& 开启 iis 的 WebSocket 协议
using System.IO;
using System.Net.WebS
using System.T
using System.T
using System.W
namespace WebServer
public class WebSocketServer : IHttpHandler
// 接收数据的缓冲区的最大大小
private int _maxBufferSize = 64 * 1024;
public void ProcessRequest(HttpContext context)
// HttpContext.AcceptWebSocketRequest() - 接受一个 WebSocket 请求
context.AcceptWebSocketRequest(async wsContext =& // AspNetWebSocketContext
byte[] receiveBuffer = new byte[_maxBufferSize];
ArraySegment&byte& buffer = new ArraySegment&byte&(receiveBuffer);
// AspNetWebSocketContext.WebSocket - 获取当前上下文的 WebSocket 对象
WebSocket socket = wsContext.WebS
// HTTP 握手完成
if (socket.State == WebSocketState.Open)
var outputString = "WebSocket Connected: " + DateTime.Now.ToString("mm:ss");
ArraySegment&byte& outputBuffer = new ArraySegment&byte&(Encoding.UTF8.GetBytes(outputString));
// WebSocket.SendAsync() - 发送数据
WebSocketMessageType.Text - 发送的是文本数据
WebSocketMessageType.Binary - 发送的是二进制数据
await socket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
// HTTP 握手完成
while (socket.State == WebSocketState.Open)
// WebSocket.ReceiveAsync() - 接收数据,返回 WebSocketReceiveResult 对象
WebSocketReceiveResult receiveResult = await socket.ReceiveAsync(buffer, CancellationToken.None);
// WebSocketReceiveResult.MessageType - 接收到的数据的类型(WebSocketMessageType 枚举)
WebSocketMessageType.Text - 收到的是文本数据
WebSocketMessageType.Binary - 收到的是二进制数据
WebSocketMessageType.Close - 收到的是来自客户端的 WebSocket 关闭的消息
if (receiveResult.MessageType == WebSocketMessageType.Close)
// WebSocket.CloseAsync() - 关闭 WebSocket
await socket.CloseAsync(
receiveResult.CloseStatus.GetValueOrDefault(),
receiveResult.CloseStatusDescription,
CancellationToken.None);
int offset = receiveResult.C
// WebSocketReceiveResult.EndOfMessage - 消息是否被完全接收
while (receiveResult.EndOfMessage == false)
// WebSocket.ReceiveAsync() - 接收数据,返回 WebSocketReceiveResult 对象
receiveResult = await socket.ReceiveAsync(new ArraySegment&byte&(receiveBuffer, offset, _maxBufferSize - offset), CancellationToken.None);
offset += receiveResult.C
// 收到文本数据
if (receiveResult.MessageType == WebSocketMessageType.Text)
string receivedText = Encoding.UTF8.GetString(receiveBuffer, 0, offset);
string sendText = "server to client: \"" + receivedText + "\"";
// 发送文本数据到客户端
ArraySegment&byte& outputBuffer = new ArraySegment&byte&(Encoding.UTF8.GetBytes(sendText));
await socket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
// 收到二进制数据
else if (receiveResult.MessageType == WebSocketMessageType.Binary)
string sendText = "server to client: binary message received, size: " + receiveResult.Count + " bytes";
// 发送文本数据到客户端
ArraySegment&byte& outputBuffer = new ArraySegment&byte&(Encoding.UTF8.GetBytes(sendText));
await socket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
catch (Exception ex)
catch (Exception ex)
public bool IsReusable
return false;
1、演示如何通过 MessageWebSocket 与 WebSocket 服务端做 Text 通信Communication/Socket/MessageWebSocketDemo.xaml
x:Class="XamlDemo.Communication.Socket.MessageWebSocketDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Communication.Socket"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"&
&Grid Background="Transparent"&
&StackPanel Margin="120 0 0 0" Orientation="Horizontal"&
&StackPanel&
&Button Name="btnTextDemo" Content="与 WebSocket 服务端做 Text 通信" Click="btnTextDemo_Click" /&
&Button Name="btnClose" Content="Close" Click="btnClose_Click" Margin="0 10 0 0" /&
&/StackPanel&
&TextBlock Name="lblMsg" FontSize="14.667" TextWrapping="Wrap" Margin="20 0 0 0" /&
&/StackPanel&
Communication/Socket/MessageWebSocketDemo.xaml.cs
* 演示如何通过 MessageWebSocket 与 WebSocket 服务端做 Text 通信
* 注:需要在 Package.appxmanifest 中增加配置 &Capability Name="privateNetworkClientServer" /& 和 &Capability Name="internetClient" /&
using Windows.Networking.S
using Windows.Storage.S
using Windows.UI.C
using Windows.UI.X
using Windows.UI.Xaml.C
using Windows.W
namespace XamlDemo.Communication.Socket
public sealed partial class MessageWebSocketDemo : Page
// WebSocket 协议的服务端地址(服务端代码参见:WebServer/WebSocketServer.cs)
private Uri _serverUri = new Uri("ws://localhost:86/WebSocketServer.ashx");
// MessageWebSocket - 用于与 WebSocket 服务端做 Message 通信(可以是 utf8 或 binary)
private MessageWebSocket _
// 用于发送数据
DataWriter _dataW
public MessageWebSocketDemo()
this.InitializeComponent();
private async void btnTextDemo_Click(object sender, RoutedEventArgs e)
if (_socket == null)
lblMsg.Text += "connecting to: " + _serverUri.ToString();
lblMsg.Text += Environment.NewL
_socket = new MessageWebSocket();
// 发送的消息的类型 Utf8 或 Binary
_socket.Control.MessageType = SocketMessageType.Utf8;
// 接收到消息时所触发的事件
_socket.MessageReceived += _socket_MessageR
// WebSocket 关闭时所触发的事件
_socket.Closed += async (senderSocket, args) =&
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
// WebSocketClosedEventArgs.Code - 关闭原因的状态吗
// WebSocketClosedEventArgs.Reason - 关闭原因的详细信息
lblMsg.Text += "socket closed - code: " + args.Code + ", reason: " + args.R
lblMsg.Text += Environment.NewL
if (_socket != null)
_socket.Dispose();
_socket = null;
// 连接指定的 WebSocket 服务
await _socket.ConnectAsync(_serverUri);
// 根据 MessageWebSocket 的 OutputStream,实例化一个 DataWriter,以便发数据到服务端
_dataWriter = new DataWriter(_socket.OutputStream);
lblMsg.Text += "connected";
lblMsg.Text += Environment.NewL
string message = "hello " + DateTime.Now.ToString("hh:mm:ss");
lblMsg.Text += "send: " +
lblMsg.Text += Environment.NewL
// 发送数据到服务端
_dataWriter.WriteString(message);
await _dataWriter.StoreAsync();
lblMsg.Text += "sent";
lblMsg.Text += Environment.NewL
catch (Exception ex)
if (_socket != null)
_socket.Dispose();
_socket = null;
WebErrorStatus errStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult);
lblMsg.Text += "errStatus: " + errStatus.ToString();
lblMsg.Text += Environment.NewL
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewL
void _socket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
// MessageWebSocketMessageReceivedEventArgs.MessageType - 收到的数据的类型 Utf8 或 Binary
// MessageWebSocketMessageReceivedEventArgs.GetDataReader() - 获取收到的数据的 DataReader 对象,用于读取接收到的数据
using (DataReader reader = args.GetDataReader())
reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
string read = reader.ReadString(reader.UnconsumedBufferLength);
var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
lblMsg.Text += "received: " +
lblMsg.Text += Environment.NewL
catch (Exception ex)
WebErrorStatus errStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult);
lblMsg.Text += "errStatus: " + errStatus.ToString();
lblMsg.Text += Environment.NewL
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewL
private void btnClose_Click(object sender, RoutedEventArgs e)
if (_socket != null)
lblMsg.Text += "socket closing";
lblMsg.Text += Environment.NewL
// 关闭 WebSocket,可以指定 code 和 reason(此处指定的 code 和 reason 可以在 MessageWebSocket.Closed 事件中获取)
_socket.Close(8888, "用户在客户端关闭了 WebSocket");
_socket = null;
catch (Exception ex)
WebErrorStatus errStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult);
lblMsg.Text += "errStatus: " + errStatus.ToString();
lblMsg.Text += Environment.NewL
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewL
2、演示如何通过 StreamWebSocket 与 WebSocket 服务端做 Stream(Binary) 通信Communication/Socket/StreamWebSocketDemo.xaml
x:Class="XamlDemo.Communication.Socket.StreamWebSocketDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Communication.Socket"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"&
&Grid Background="Transparent"&
&StackPanel Margin="120 0 0 0" Orientation="Horizontal"&
&StackPanel&
&Button Name="btnBinaryDemo" Content="与 WebSocket 服务端做 Binary 通信" Click="btnBinaryDemo_Click" /&
&Button Name="btnClose" Content="Close" Click="btnClose_Click" Margin="0 10 0 0" /&
&/StackPanel&
&TextBlock Name="lblMsg" FontSize="14.667" TextWrapping="Wrap" Margin="20 0 0 0" /&
&/StackPanel&
Communication/Socket/StreamWebSocketDemo.xaml.cs
* 演示如何通过 StreamWebSocket 与 WebSocket 服务端做 Stream(Binary) 通信
* 注:需要在 Package.appxmanifest 中增加配置 &Capability Name="privateNetworkClientServer" /& 和 &Capability Name="internetClient" /&
using Windows.Networking.S
using Windows.Storage.S
using Windows.UI.C
using Windows.UI.X
using Windows.UI.Xaml.C
using Windows.W
using System.Runtime.InteropServices.WindowsR
using System.Threading.T
using System.IO;
namespace XamlDemo.Communication.Socket
public sealed partial class StreamWebSocketDemo : Page
// WebSocket 协议的服务端地址(服务端代码参见:WebServer/WebSocketServer.cs)
private Uri _serverUri = new Uri("ws://localhost:86/WebSocketServer.ashx");
// StreamWebSocket - 用于与 WebSocket 服务端做 Stream 通信(只能是 binary)
private StreamWebSocket _
public StreamWebSocketDemo()
this.InitializeComponent();
private async void btnBinaryDemo_Click(object sender, RoutedEventArgs e)
if (_socket == null)
lblMsg.Text += "connecting to: " + _serverUri.ToString();
lblMsg.Text += Environment.NewL
_socket = new StreamWebSocket();
// WebSocket 关闭时所触发的事件
_socket.Closed += async (senderSocket, args) =&
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
// WebSocketClosedEventArgs.Code - 关闭原因的状态吗
// WebSocketClosedEventArgs.Reason - 关闭原因的详细信息
lblMsg.Text += "socket closed - code: " + args.Code + ", reason: " + args.R
lblMsg.Text += Environment.NewL
if (_socket != null)
_socket.Dispose();
_socket = null;
// 连接指定的 WebSocket 服务
await _socket.ConnectAsync(_serverUri);
// 新开线程,用于接收数据
Task receiving = Task.Factory.StartNew(ReceiveData, _socket.InputStream.AsStreamForRead(), TaskCreationOptions.LongRunning);
// 新开线程,用于发送数据
Task sending = Task.Factory.StartNew(SendData, _socket.OutputStream, TaskCreationOptions.LongRunning);
lblMsg.Text += "connected";
lblMsg.Text += Environment.NewL
catch (Exception ex)
if (_socket != null)
_socket.Dispose();
_socket = null;
WebErrorStatus errStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult);
lblMsg.Text += "errStatus: " + errStatus.ToString();
lblMsg.Text += Environment.NewL
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewL
// 发送数据
private async void SendData(object state)
// 自定义需要发送的二进制数据
byte[] data = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
IOutputStream writeStream = (IOutputStream)
while (true)
var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
lblMsg.Text += "send: " + data.Length.ToString() + " 字节的数据";
lblMsg.Text += Environment.NewL
// 发送 stream 数据
await writeStream.WriteAsync(data.AsBuffer());
var ignore2 = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
lblMsg.Text += "sent";
lblMsg.Text += Environment.NewL
await Task.Delay(TimeSpan.FromSeconds(3));
catch (ObjectDisposedException)
var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
lblMsg.Text += "用于发送数据的后台线程已经停止";
lblMsg.Text += Environment.NewL
catch (Exception ex)
WebErrorStatus errStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult);
var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
lblMsg.Text += "errStatus: " + errStatus.ToString();
lblMsg.Text += Environment.NewL
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewL
// 接收数据
private async void ReceiveData(object state)
// 用于接收数据的缓冲区
byte[] readBuffer = new byte[1024];
int bytesReceived = 0;
Stream readStream = (Stream)
while (true)
// 接收数据
int read = await readStream.ReadAsync(readBuffer, 0, readBuffer.Length);
bytesReceived +=
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
lblMsg.Text += "received: " + System.Text.Encoding.UTF8.GetString(readBuffer, 0, read);
lblMsg.Text += Environment.NewL
lblMsg.Text += "累计已收到 " + bytesReceived.ToString() + " 字节的数据";
lblMsg.Text += Environment.NewL
catch (ObjectDisposedException)
var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
lblMsg.Text += "用于接收数据的后台线程已经停止";
lblMsg.Text += Environment.NewL
catch (Exception ex)
WebErrorStatus errStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult);
var ignore = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =&
lblMsg.Text += "errStatus: " + errStatus.ToString();
lblMsg.Text += Environment.NewL
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewL
private void btnClose_Click(object sender, RoutedEventArgs e)
if (_socket != null)
lblMsg.Text += "socket closing";
lblMsg.Text += Environment.NewL
// 关闭 WebSocket,可以指定 code 和 reason(此处指定的 code 和 reason 可以在 MessageWebSocket.Closed 事件中获取)
_socket.Close(8888, "用户在客户端关闭了 WebSocket");
_socket = null;
catch (Exception ex)
WebErrorStatus errStatus = WebSocketError.GetStatus(ex.GetBaseException().HResult);
lblMsg.Text += "errStatus: " + errStatus.ToString();
lblMsg.Text += Environment.NewL
lblMsg.Text += ex.ToString();
lblMsg.Text += Environment.NewL扫一扫体验手机阅读
从不用 try-catch 实现的 async/await 语法说错误处理
<span type="1" blog_id="2062422" userid='
72篇文章,35W+人气,229粉丝
<span type="1" blog_id="2062422" userid='背水一战 Windows 10 (89) - 文件系统: 读写文本数据, 读写二进制数据, 读写流数据 - webabcd - 博客园
posts - 615, comments - 10475, trackbacks - 594, articles - 0
背水一战 Windows 10 (89) - 文件系统: 读写文本数据, 读写二进制数据, 读写流数据
作者:介绍背水一战 Windows 10 之&文件系统
读写文本数据
读写二进制数据
读写流数据
示例1、演示如何读写文本数据FileSystem/ReadWriteText.xaml
x:Class="Windows10.FileSystem.ReadWriteText"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows10.FileSystem"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"&
&Grid Background="Transparent"&
&StackPanel Margin="10 0 10 10"&
&TextBlock Name="lblMsg" Margin="5" /&
&Button Name="btnWriteText" Content="Write Text" Click="btnWriteText_Click" Margin="5" /&
&Button Name="btnReadText" Content="Read Text" Click="btnReadText_Click" Margin="5" /&
&/StackPanel&
FileSystem/ReadWriteText.xaml.cs
* 演示如何读写文本数据
* FileIO - 用于读写 IStorageFile 对象的帮助类
WriteTextAsync() - 将指定的文本数据写入到指定的文件
AppendTextAsync() - 将指定的文本数据追加到指定的文件
WriteLinesAsync() - 将指定的多段文本数据写入到指定的文件
AppendLinesAsync() - 将指定的多段文本数据追加到指定的文件
ReadTextAsync() - 获取指定的文件中的文本数据
ReadLinesAsync() - 获取指定的文件中的文本数据,返回的是一行一行的数据
using Windows.S
using Windows.UI.X
using Windows.UI.Xaml.C
namespace Windows10.FileSystem
public sealed partial class ReadWriteText : Page
public ReadWriteText()
this.InitializeComponent();
private async void btnWriteText_Click(object sender, RoutedEventArgs e)
// 在指定的目录下创建指定的文件
StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdText.txt", CreationCollisionOption.ReplaceExisting);
// 在指定的文件中写入指定的文本
string textContent = "I am webabcd";
await FileIO.WriteTextAsync(storageFile, textContent, Windows.Storage.Streams.UnicodeEncoding.Utf8); // 编码为 UnicodeEncoding.Utf8
lblMsg.Text = "写入成功";
private async void btnReadText_Click(object sender, RoutedEventArgs e)
// 在指定的目录下获取指定的文件
StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
StorageFile storageFile = await storageFolder.GetFileAsync("webabcdText.txt");
if (storageFile != null)
// 获取指定的文件中的文本内容
string textContent = await FileIO.ReadTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.Utf8); // 编码为 UnicodeEncoding.Utf8
lblMsg.Text = "读取结果:" + textC
2、演示如何读写二进制数据FileSystem/ReadWriteBinary.xaml
x:Class="Windows10.FileSystem.ReadWriteBinary"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows10.FileSystem"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"&
&Grid Background="Transparent"&
&StackPanel Margin="10 0 10 10"&
&TextBlock Name="lblMsg" Margin="5" /&
&Button Name="btnWriteBinary" Content="Write Binary" Click="btnWriteBinary_Click" Margin="5" /&
&Button Name="btnReadBinary" Content="Read Binary" Click="btnReadBinary_Click" Margin="5" /&
&/StackPanel&
FileSystem/ReadWriteBinary.xaml.cs
* 演示如何读写二进制数据
* FileIO - 用于读写 IStorageFile 对象的帮助类
WriteBufferAsync() - 将指定的二进制数据写入指定的文件
ReadBufferAsync() - 获取指定的文件中的二进制数据
* IBuffer - 字节数组
using Windows.S
using Windows.Storage.S
using Windows.UI.X
using Windows.UI.Xaml.C
namespace Windows10.FileSystem
public sealed partial class ReadWriteBinary : Page
public ReadWriteBinary()
this.InitializeComponent();
private async void btnWriteBinary_Click(object sender, RoutedEventArgs e)
// 在指定的目录下创建指定的文件
StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdBinary.txt", CreationCollisionOption.ReplaceExisting);
// 将字符串转换成二进制数据,并保存到指定文件
string textContent = "I am webabcd";
IBuffer buffer = ConverterHelper.String2Buffer(textContent);
await FileIO.WriteBufferAsync(storageFile, buffer);
lblMsg.Text = "写入成功";
private async void btnReadBinary_Click(object sender, RoutedEventArgs e)
// 在指定的目录下获取指定的文件
StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
StorageFile storageFile = await storageFolder.GetFileAsync("webabcdBinary.txt");
if (storageFile != null)
// 获取指定文件中的二进制数据,将其转换成字符串并显示
IBuffer buffer = await FileIO.ReadBufferAsync(storageFile);
string textContent = ConverterHelper.Buffer2String(buffer);
lblMsg.Text = "读取结果:" + textC
3、演示如何读写流数据FileSystem/ReadWriteStream.xaml
x:Class="Windows10.FileSystem.ReadWriteStream"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows10.FileSystem"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"&
&Grid Background="Transparent"&
&StackPanel Margin="10 0 10 10"&
&TextBlock Name="lblMsg" Margin="5" /&
&Button Name="btnWriteStream1" Content="Write Stream(通过 IRandomAccessStream 写)" Click="btnWriteStream1_Click" Margin="5" /&
&Button Name="btnWriteStream2" Content="Write Stream(通过 StorageStreamTransaction 写)" Click="btnWriteStream2_Click" Margin="5" /&
&Button Name="btnReadStream" Content="Read Stream" Click="btnReadStream_Click" Margin="5" /&
&/StackPanel&
FileSystem/ReadWriteStream.xaml.cs
* 演示如何读写流数据
* IBuffer - 字节数组
* IInputStream - 支持读取的流
* IOutputStream - 支持写入的流
* IRandomAccessStream - 支持读取和写入的流,其继承自 IInputStream 和 IOutputStream
* DataReader - 数据读取器,用于从数据流中读取数据
LoadAsync() - 从数据流中加载指定长度的数据到缓冲区
ReadInt32(), ReadByte(), ReadString() 等 - 从缓冲区中读取数据
* DataWriter - 数据写入器,用于将数据写入数据流
WriteInt32(), WriteByte(), WriteString() 等 - 将数据写入缓冲区
StoreAsync() - 将缓冲区中的数据保存到数据流
* StorageStreamTransaction - 用于写数据流到文件的类(它写文件的方式是:先写临时文件,然后临时文件重命名)
Stream - 数据流(只读)
CommitAsync - 重命名临时文件
* StorageFile - 文件操作类
public IAsyncOperation&IRandomAccessStream& OpenAsync(FileAccessMode accessMode) - 打开文件,返回 IRandomAccessStream 对象
public IAsyncOperation&IRandomAccessStream& OpenAsync(FileAccessMode accessMode, StorageOpenOptions options) - 打开文件,返回 IRandomAccessStream 对象
FileAccessMode.Read - 返回的流可读,不可写
FileAccessMode.ReadWrite - 返回的流可读,可写
StorageOpenOptions.AllowOnlyReaders - 其他调用者可读不可写
StorageOpenOptions.AllowReadersAndWriters - 其他调用者可读可写
public IAsyncOperation&StorageStreamTransaction& OpenTransactedWriteAsync() - 打开文件,返回 StorageStreamTransaction 对象
public IAsyncOperation&StorageStreamTransaction& OpenTransactedWriteAsync(StorageOpenOptions options) - 打开文件,返回 StorageStreamTransaction 对象
using Windows.S
using Windows.Storage.S
using Windows.UI.X
using Windows.UI.Xaml.C
namespace Windows10.FileSystem
public sealed partial class ReadWriteStream : Page
public ReadWriteStream()
this.InitializeComponent();
// Write Stream(通过 IRandomAccessStream 写)
private async void btnWriteStream1_Click(object sender, RoutedEventArgs e)
// 在指定的目录下创建指定的文件
StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdStream.txt", CreationCollisionOption.ReplaceExisting);
string textContent = "I am webabcd(IRandomAccessStream)";
if (storageFile != null)
using (IRandomAccessStream randomStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
using (DataWriter dataWriter = new DataWriter(randomStream))
// 将字符串写入数据流
dataWriter.WriteString(textContent);
// 将数据流写入文件
await dataWriter.StoreAsync();
lblMsg.Text = "写入成功";
// Write Stream(通过 StorageStreamTransaction 写)
private async void btnWriteStream2_Click(object sender, RoutedEventArgs e)
// 在指定的目录下创建指定的文件
StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdStream.txt", CreationCollisionOption.ReplaceExisting);
string textContent = "I am webabcd(StorageStreamTransaction)";
using (StorageStreamTransaction transaction = await storageFile.OpenTransactedWriteAsync())
using (DataWriter dataWriter = new DataWriter(transaction.Stream))
// 将字符串写入数据流
dataWriter.WriteString(textContent);
// 使用 StorageStreamTransaction 方式的话,调用 DataWriter 的 StoreAsync() 方法的作用是把数据写入临时文件
// 以本例为例,这个临时文件就是同目录下名为 webabcdStream.txt.~tmp 的文件。只要不调用 CommitAsync() 方法的话就会看到
// 返回值为写入数据的大小,需要通过此值更新 StorageStreamTransaction 中的 Stream 的大小
transaction.Stream.Size = await dataWriter.StoreAsync();
// 重命名临时文件
await transaction.CommitAsync();
lblMsg.Text = "写入成功";
private async void btnReadStream_Click(object sender, RoutedEventArgs e)
// 在指定的目录下获取指定的文件
StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary);
StorageFile storageFile = await storageFolder.GetFileAsync("webabcdStream.txt");
if (storageFile != null)
using (IRandomAccessStream randomStream = await storageFile.OpenAsync(FileAccessMode.Read))
using (DataReader dataReader = new DataReader(randomStream))
ulong size = randomStream.S
if (size &= uint.MaxValue)
// 从数据流中读取数据
uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
// 将读取到的数据转换为字符串
string fileContent = dataReader.ReadString(numBytesLoaded);
lblMsg.Text = "读取结果:" + fileC

我要回帖

更多关于 es7 async await 的文章

 

随机推荐