當前位置: 首頁>>代碼示例>>C#>>正文


C# DataWriter.WriteString方法代碼示例

本文整理匯總了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());
   
       }
開發者ID:Hitchhikrr,項目名稱:NokiaCompo_CampusParty13,代碼行數:11,代碼來源:writeTag.xaml.cs

示例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();
            }
        }
開發者ID:j0z,項目名稱:PlayM,代碼行數:31,代碼來源:Client.cs

示例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();
                }
            }
        }
開發者ID:tomasmcguinness,項目名稱:BeCharming,代碼行數:30,代碼來源:ShareTargetsManager.cs

示例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();
                }
            }
        }
開發者ID:xyzzer,項目名稱:WinRTXamlToolkit,代碼行數:38,代碼來源:StringIOExtensions.cs

示例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);
            }
        }
開發者ID:Injac,項目名稱:NIteLIteCommander,代碼行數:35,代碼來源:MainPage.xaml.cs

示例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();
 }
開發者ID:forehalo,項目名稱:UWP-dev,代碼行數:35,代碼來源:_DataWriter.xaml.cs

示例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();
     }
 }
開發者ID:mac10688,項目名稱:PublicWorkspace,代碼行數:33,代碼來源:Scenario4.xaml.cs

示例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);
        }
開發者ID:GregOnNet,項目名稱:WP8BookSamples,代碼行數:29,代碼來源:MainPage.xaml.cs

示例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;
     }
 }
開發者ID:ballance,項目名稱:MetroTorrent,代碼行數:28,代碼來源:ServerCommunicator.cs

示例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)
                {

                }
            }
        }
開發者ID:peepo3663,項目名稱:WindowsPhone8,代碼行數:27,代碼來源:MainPage.xaml.cs

示例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());
 }
開發者ID:mderoode,項目名稱:OVCClient,代碼行數:26,代碼來源:SocketConnection.xaml.cs

示例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);
                    }
                }
            }
        }
開發者ID:KonstantinKolesnik,項目名稱:SmartHub,代碼行數:29,代碼來源:WemosTransport.cs

示例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();
         }
     }
 }
開發者ID:undwad,項目名稱:2Desktop,代碼行數:26,代碼來源:App.xaml.cs

示例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();
            }
        }
開發者ID:RajaBellebon,項目名稱:edX,代碼行數:31,代碼來源:Shipper.cs

示例15: WriteToSerialPort

 public async void WriteToSerialPort(string message)
 {
     var writer = new DataWriter(_realDevice.OutputStream);
     writer.WriteString(AddNewLine(message));
     await writer.StoreAsync().AsTask();
     writer.DetachStream();
 }
開發者ID:Quantzo,項目名稱:IotRouter,代碼行數:7,代碼來源:SerialBridge.cs


注:本文中的Windows.Storage.Streams.DataWriter.WriteString方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。