本文整理汇总了C#中Windows.Storage.Streams.DataWriter.WriteString方法的典型用法代码示例。如果您正苦于以下问题:C# DataWriter.WriteString方法的具体用法?C# DataWriter.WriteString怎么用?C# DataWriter.WriteString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.DataWriter
的用法示例。
在下文中一共展示了DataWriter.WriteString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnWriteableTagArrived
private void OnWriteableTagArrived(ProximityDevice sender, ProximityMessage message)
{
var dataWriter = new DataWriter();
dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
string appLauncher = string.Format(@"mywaiter:MainPage?source=3");
dataWriter.WriteString(appLauncher);
pubId = sender.PublishBinaryMessage("WindowsUri:WriteTag", dataWriter.DetachBuffer());
}
示例2: send
/// <summary>
/// Send the message to the server
/// </summary>
/// <param name="type">KB or M</param>
/// <param name="message">Single character or x,y</param>
/// <param name="hold">0=default, 1=press, 2=release</param>
public void send(string type, string message, int hold = 0)
{
try
{
//NetworkStream clientStream = client.GetStream();
DataWriter writer = new DataWriter(client.OutputStream);
//ASCIIEncoding encoder = new ASCIIEncoding();
string buffer = type + ';' + message + ';' + hold + "\n";
writer.WriteUInt32(writer.MeasureString(buffer));
writer.WriteString(buffer);
/*
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
* */
writer.WriteString(buffer);
}
catch
{
//Console.WriteLine("Connection Lost");
startClient();
}
}
示例3: PerformPeerDiscovery
public async void PerformPeerDiscovery()
{
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
if (socket == null)
{
socket = new DatagramSocket();
socket.MessageReceived += socket_MessageReceived;
try
{
await socket.BindEndpointAsync(null, "22002");
}
catch
{
// Swallow any already bound exceptions!
}
}
using (var outputStream = await socket.GetOutputStreamAsync(new HostName("230.0.0.1"), "22003"))
{
using (DataWriter wr = new DataWriter(outputStream))
{
wr.WriteString("**BECHARMING DISCOVERY**");
await wr.FlushAsync();
await wr.StoreAsync();
}
}
}
示例4: SaveAsync
/// <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();
}
}
}
示例5: WriteBlecOmmand
private async Task WriteBlecOmmand(string command)
{
try
{
_commandExecuting = true;
BluetoothLEDevice oygenBluetoothLeDevice = null;
GattCharacteristic writeCharacteristics = null;
oygenBluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(0x000780067cf1);
var srv =
oygenBluetoothLeDevice.GattServices.FirstOrDefault(
gs => gs.Uuid.ToString().Equals("2ac94b65-c8f4-48a4-804a-c03bc6960b80"));
Debug.WriteLine(oygenBluetoothLeDevice.Name);
writeCharacteristics =
srv
.GetAllCharacteristics()
.FirstOrDefault(ch => ch.Uuid.ToString().Equals("50e03f22-b496-4a73-9e85-335482ed4b12"));
var writer = new DataWriter();
writer.WriteString(command + "\n");
await writeCharacteristics.WriteValueAsync(writer.DetachBuffer());
}
catch (Exception ex)
{
Debug.WriteLine("Bluetooth Problem.");
Debug.WriteLine(ex.Message);
}
}
示例6: OnWrite
private async void OnWrite(Object sender, RoutedEventArgs e)
{
// 获取本地目录的引用
StorageFolder local = ApplicationData.Current.LocalFolder;
// 创建新文件
StorageFile newFIle = await local.CreateFileAsync("demo.dat", CreationCollisionOption.ReplaceExisting);
// 打开文件流
using(IRandomAccessStream stream = await newFIle.OpenAsync(FileAccessMode.ReadWrite))
{
// 实例化 DataWriter
DataWriter dw = new DataWriter(stream);
// 设置默认编码格式
dw.UnicodeEncoding = UnicodeEncoding.Utf8;
// 写入 bool 值
dw.WriteBoolean(true);
// 写入日期值
DateTime dt = new DateTime(2010, 8, 21);
dw.WriteDateTime(dt);
// 写入字符串
string str = "测试文本";
// 计算字符串长度
uint len = dw.MeasureString(str);
// 先写入字符串的长的
dw.WriteUInt32(len);
// 再写入字符串
dw.WriteString(str);
// 以下方法必须调用
await dw.StoreAsync();
// 解除 DataWriter 与流的关联
dw.DetachStream();
dw.Dispose();
}
MessageDialog msgDlg = new MessageDialog("保存成功。");
await msgDlg.ShowAsync();
}
示例7: WriteToStreamButton_Click
private async void WriteToStreamButton_Click(object sender, RoutedEventArgs e)
{
try
{
rootPage.ResetScenarioOutput(OutputTextBlock);
StorageFile file = rootPage.sampleFile;
if (file != null)
{
string userContent = InputTextBox.Text;
if (!String.IsNullOrEmpty(userContent))
{
using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
{
using (DataWriter dataWriter = new DataWriter(transaction.Stream))
{
dataWriter.WriteString(userContent);
transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file
await transaction.CommitAsync();
OutputTextBlock.Text = "The following text was written to '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + userContent;
}
}
}
else
{
OutputTextBlock.Text = "The text box is empty, please write something and then click 'Write' again.";
}
}
}
catch (FileNotFoundException)
{
rootPage.NotifyUserFileNotExist();
}
}
示例8: OnLoadingFile
private async void OnLoadingFile(object sender, GestureEventArgs e)
{
var city = new City
{
Name = "Leipzig",
State = "Saxony",
Country = "Germany",
Population = 550000
};
string json = JsonConvert.SerializeObject(city);
var cityFile =
await ApplicationData.Current
.LocalFolder.CreateFileAsync(
"leipzig.city",
CreationCollisionOption.ReplaceExisting);
using (var stream = await cityFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var writer = new DataWriter(stream))
{
writer.WriteString(json);
await writer.StoreAsync();
}
}
Launcher.LaunchFileAsync(cityFile);
}
示例9: SendMessage
public async void SendMessage(string msg)
{
HostName hostName;
try
{
hostName = new HostName("localhost");
}
catch (ArgumentException)
{
return;
}
StreamSocket socket;
try
{
using (socket = new StreamSocket())
{
await socket.ConnectAsync(hostName, port2);
//CoreApplication.Properties.Add("connected", null);
DataWriter dw = new DataWriter(socket.OutputStream);
dw.WriteString(msg);
await dw.StoreAsync();
}
}
catch
{
//break;
}
}
示例10: datagramSocket_MessageReceived
async void datagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
i++;
DataReader dataReader = args.GetDataReader();
uint length = dataReader.UnconsumedBufferLength;
string content = dataReader.ReadString(length);
Deployment.Current.Dispatcher.BeginInvoke(() =>
msgList.Children.Add(new TextBlock { Text = "服务器收到的消息:" + content }));
//HostName hostName = new HostName("localhost");
//DatagramSocket datagramSocket = new DatagramSocket();
//IOutputStream outputStream = await datagramSocket.GetOutputStreamAsync(hostName, "22112");
DataWriter writer = new DataWriter(sender.OutputStream);
writer.WriteString(content + "|" + i);
try
{
await writer.StoreAsync();
msgList.Children.Add(new TextBlock { Text = "服务器发送的消息:" + content + "|" + i });
}
catch (Exception err)
{
if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
{
}
}
}
示例11: DoCommand
private async Task<string> DoCommand(string command)
{
StringBuilder strBuilder = new StringBuilder();
using (StreamSocket clientSocket = new StreamSocket())
{
await clientSocket.ConnectAsync(new HostName("192.168.9.108"), "9001");
using (DataWriter writer = new DataWriter(clientSocket.OutputStream))
{
writer.WriteString(command);
await writer.StoreAsync();
writer.DetachStream();
}
using (DataReader reader = new DataReader(clientSocket.InputStream))
{
reader.InputStreamOptions = InputStreamOptions.Partial;
await reader.LoadAsync(8192);
while (reader.UnconsumedBufferLength > 0)
{
strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(8192);
}
reader.DetachStream();
}
}
return (strBuilder.ToString());
}
示例12: Send
public async Task Send(WemosMessage msg)
{
if (msg != null)
{
var str = msg.ToDto();
if (!string.IsNullOrEmpty(str))
{
try
{
// GetOutputStreamAsync can be called multiple times on a single DatagramSocket instance to obtain
// IOutputStreams pointing to various different remote endpoints. The remote hostname given to
// GetOutputStreamAsync can be a unicast, multicast or broadcast address.
IOutputStream outputStream = await listenerSocket.GetOutputStreamAsync(new HostName(remoteMulticastAddress), remoteService);
DataWriter writer = new DataWriter(outputStream);
writer.WriteString(str);
await writer.StoreAsync();
}
catch (Exception exception)
{
// If this is an unknown status it means that the error is fatal and retry will likely fail.
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
throw;
//rootPage.NotifyUser("Send failed with error: " + exception.Message, NotifyType.ErrorMessage);
}
}
}
}
示例13: OnShareTargetActivated
protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
if (args.ShareOperation.Data.Contains(StandardDataFormats.WebLink))
{
Uri uri = await args.ShareOperation.Data.GetWebLinkAsync();
if (null != uri)
try
{
using (var socket = new MessageWebSocket())
{
socket.Control.MessageType = SocketMessageType.Utf8;
await socket.ConnectAsync(new Uri("ws://" + settings["Host"].ToString() + ":" + settings["Port"].ToString()));
using (var writer = new DataWriter(socket.OutputStream))
{
writer.WriteString(uri.AbsoluteUri);
await writer.StoreAsync();
args.ShareOperation.ReportCompleted();
}
}
}
catch
{
show();
}
}
}
示例14: doShipping
private async void doShipping(Order order)
{
try
{
StorageFile file = await KnownFolders.DocumentsLibrary.CreateFileAsync("dispatch-" + order.OrderID.ToString() + ".txt");
if (file != null)
{
string dispatchNote = "Order Summary: " +
"\r\nOrder ID: " + order.OrderID +
"\r\nOrder Total: " + String.Format("{0:C}", order.TotalValue);
var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
var writeStream = stream.GetOutputStreamAt(0);
DataWriter writer = new DataWriter(writeStream);
writer.WriteString(dispatchNote);
await writer.StoreAsync();
await writeStream.FlushAsync();
writeStream.Dispose();
}
else
{
MessageDialog dlg = new MessageDialog(String.Format("Unable to save to file: {0}", file.DisplayName), "Not saved");
dlg.ShowAsync();
}
}
catch (Exception ex)
{
MessageDialog dlg = new MessageDialog(ex.Message, "Exception");
dlg.ShowAsync();
}
}
示例15: WriteToSerialPort
public async void WriteToSerialPort(string message)
{
var writer = new DataWriter(_realDevice.OutputStream);
writer.WriteString(AddNewLine(message));
await writer.StoreAsync().AsTask();
writer.DetachStream();
}