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


C# DataWriter.Dispose方法代码示例

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


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

示例1: WriteAllText

 public void WriteAllText(string filename, string text, Action completed)
 {
     StorageFolder localFolder = 
                     ApplicationData.Current.LocalFolder;
     IAsyncOperation<StorageFile> createOp = 
                     localFolder.CreateFileAsync(filename,
                         CreationCollisionOption.ReplaceExisting);
     createOp.Completed = (asyncInfo1, asyncStatus1) =>
     {
         IStorageFile storageFile = asyncInfo1.GetResults();
         IAsyncOperation<IRandomAccessStream> openOp = 
                 storageFile.OpenAsync(FileAccessMode.ReadWrite);
         openOp.Completed = (asyncInfo2, asyncStatus2) =>
         {
             IRandomAccessStream stream = asyncInfo2.GetResults();
             DataWriter dataWriter = new DataWriter(stream);
             dataWriter.WriteString(text);
             DataWriterStoreOperation storeOp = 
                     dataWriter.StoreAsync();
             storeOp.Completed = (asyncInfo3, asyncStatus3) =>
             {
                 dataWriter.Dispose();
                 completed();
             };
         };
     };
 }
开发者ID:karanga,项目名称:xamarin-forms-book-preview,代码行数:27,代码来源:FileHelper.cs

示例2: WriteToOutputStreamAsync

		private async Task WriteToOutputStreamAsync(byte[] bytes)
		{

			if (_socket == null) return;
			_writer = new DataWriter(_socket.OutputStream);
			_writer.WriteBytes(bytes);

			var debugString = UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length);

			try
			{
				await _writer.StoreAsync();
				await _socket.OutputStream.FlushAsync();

				_writer.DetachStream();
				_writer.Dispose();
			}
			catch (Exception exception)
			{
				// If this is an unknown status it means that the error if fatal and retry will likely fail.
				if (global::Windows.Networking.Sockets.SocketError.GetStatus(exception.HResult) == global::Windows.Networking.Sockets.SocketErrorStatus.Unknown)
				{
					// TODO abort any retry attempts on Unity side
					throw;
				}
			}
		}
开发者ID:kungfubozo,项目名称:UnityPorting,代码行数:27,代码来源:TcpClient.cs

示例3: 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

示例4: 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

示例5: Run

 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     var deferral = taskInstance.GetDeferral();
     try
     {
         var details = taskInstance.TriggerDetails as SocketActivityTriggerDetails;
         var socketInformation = details.SocketInformation;
         switch (details.Reason)
         {
             case SocketActivityTriggerReason.SocketActivity:
                 var socket = socketInformation.StreamSocket;
                 DataReader reader = new DataReader(socket.InputStream);
                 reader.InputStreamOptions = InputStreamOptions.Partial;
                 await reader.LoadAsync(250);
                 var dataString = reader.ReadString(reader.UnconsumedBufferLength);
                 ShowToast(dataString);
                 socket.TransferOwnership(socketInformation.Id);
                 break;
             case SocketActivityTriggerReason.KeepAliveTimerExpired:
                 socket = socketInformation.StreamSocket;
                 DataWriter writer = new DataWriter(socket.OutputStream);
                 writer.WriteBytes(Encoding.UTF8.GetBytes("Keep alive"));
                 await writer.StoreAsync();
                 writer.DetachStream();
                 writer.Dispose();
                 socket.TransferOwnership(socketInformation.Id);
                 break;
             case SocketActivityTriggerReason.SocketClosed:
                 socket = new StreamSocket();
                 socket.EnableTransferOwnership(taskInstance.Task.TaskId, SocketActivityConnectedStandbyAction.Wake);
                 if (ApplicationData.Current.LocalSettings.Values["hostname"] == null)
                 {
                     break;
                 }
                 var hostname = (String)ApplicationData.Current.LocalSettings.Values["hostname"];
                 var port = (String)ApplicationData.Current.LocalSettings.Values["port"];
                 await socket.ConnectAsync(new HostName(hostname), port);
                 socket.TransferOwnership(socketId);
                 break;
             default:
                 break;
         }
         deferral.Complete();
     }
     catch (Exception exception)
     {
         ShowToast(exception.Message);
         deferral.Complete();
     }
 }
开发者ID:C-C-D-I,项目名称:Windows-universal-samples,代码行数:50,代码来源:SocketActivityTask.cs

示例6: SendButton_Click

 private async void SendButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         DataWriter writer = new DataWriter(connectedSocket.OutputStream);
         writer.WriteBytes(Encoding.UTF8.GetBytes(SendMessageTextBox.Text));
         await writer.StoreAsync();
         writer.DetachStream();
         writer.Dispose();
     }
     catch(Exception exception)
     {
         rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);
     }
 }
开发者ID:t-angma,项目名称:Windows-universal-samples,代码行数:15,代码来源:scenario1_send.xaml.cs

示例7: ConvertToRandomAccessStream

        private async Task<IRandomAccessStream> ConvertToRandomAccessStream(byte[] bytes)
        {
            var randomAccessStream = new InMemoryRandomAccessStream();
            using (var writer = new DataWriter(randomAccessStream))
            {
                writer.WriteBytes(bytes);
                await writer.StoreAsync();
                await writer.FlushAsync();
                writer.DetachStream();
                writer.Dispose();
            }
            randomAccessStream.Seek(0);

            return randomAccessStream;
        }
开发者ID:Romaxaqaz,项目名称:Onliner,代码行数:15,代码来源:ImageUrlConverter.cs

示例8: send_file_tcp

        private async void send_file_tcp(String ipadd, int port)
        {            
            try
            {  
                _tcpclient = new StreamSocket();

                await _tcpclient.ConnectAsync(new HostName(ipadd), port.ToString());
                _datawriter = new DataWriter(_tcpclient.OutputStream);

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.GetFileAsync(this.filepath);

                IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync();
                
                _datareader = new DataReader(filestream);

                while ((_length = await _datareader.LoadAsync(63 * 1024)) != 0)
                {
                    _tosend = new byte[_length];

                    _datareader.ReadBytes(_tosend);

                    _datawriter.WriteBytes(_tosend);
                    await _datawriter.StoreAsync();
                }

                filestream.Dispose();
                _datareader.Dispose();
                _datawriter.Dispose();

                _tcpclient.Dispose();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _stopwatch.Stop();
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, ipadd);
            }            
        }
开发者ID:StabilityofWT,项目名称:Stability-Monitor,代码行数:43,代码来源:Wifi_agent.cs

示例9: TransferImage

        private async void TransferImage(StreamSocket socket)
        {
            var writer = new DataWriter(socket.OutputStream);

            UpdateStatus("Übertrage Bild...");

            // Anzahl der zu übertragenden Bytes übertragen
            writer.WriteInt32(App.ImageBytesToTransfer.Length);
            await writer.StoreAsync();

            // Image-Bytes übertragen
            writer.WriteBytes(App.ImageBytesToTransfer);
            await writer.StoreAsync();
            await writer.FlushAsync();

            // Ressourcen freigeben
            writer.Dispose();
            UpdateStatus("Übertragung abgeschlossen");
        }
开发者ID:GregOnNet,项目名称:WP8BookSamples,代码行数:19,代码来源:ServerPage.xaml.cs

示例10: Save

        public void Save(string filename)
        {
            string text = this.Title + "\n" + this.Text;

#if !WINDOWS_PHONE // iOS and Android

            string docsPath = Environment.GetFolderPath(
                                    Environment.SpecialFolder.Personal);
            string filepath = Path.Combine(docsPath, filename);
            File.WriteAllText(filepath, text);

#else // Windows Phone

            StorageFolder localFolder = 
                                ApplicationData.Current.LocalFolder;
            IAsyncOperation<StorageFile> createOp = 
                                localFolder.CreateFileAsync(filename, 
                                    CreationCollisionOption.ReplaceExisting);

            createOp.Completed = (asyncInfo1, asyncStatus1) =>
            {
                IStorageFile storageFile = asyncInfo1.GetResults();
                IAsyncOperation<IRandomAccessStream> openOp = 
                        storageFile.OpenAsync(FileAccessMode.ReadWrite);
                openOp.Completed = (asyncInfo2, asyncStatus2) =>
                {
                    IRandomAccessStream stream = asyncInfo2.GetResults();
                    DataWriter dataWriter = new DataWriter(stream);
                    dataWriter.WriteString(text);
                    DataWriterStoreOperation storeOp = 
                            dataWriter.StoreAsync();
                    storeOp.Completed = (asyncInfo3, asyncStatus3) =>
                    {
                        dataWriter.Dispose();
                    };
                };
            };
     
#endif
        }
开发者ID:karanga,项目名称:xamarin-forms-book-preview,代码行数:40,代码来源:Note.cs

示例11: multicastSocket_MessageReceived

		static async void multicastSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs eventArguments) {
			try {
				HostName remoteHostAddress = eventArguments.RemoteAddress;
				uint len = eventArguments.GetDataReader().UnconsumedBufferLength;
				string message = eventArguments.GetDataReader().ReadString(len).Trim();
				int p = message.IndexOf(':');
				if (p != -1) {
					string serverLogToken = message.Substring(0, p);
					int port = Int32.Parse(message.Substring(p + 1));

					if (serverLogToken == logToken && port > 0 && port < 65535) {
						Debug.WriteLine("[LOGGER] Found a Titanium log server: " + remoteHostAddress.DisplayName + ":" + port);

						try {
							tcpSocket = new StreamSocket();
							tcpSocket.Control.KeepAlive = true;
							await tcpSocket.ConnectAsync(remoteHostAddress, port.ToString());
							tcpWriter = new DataWriter(tcpSocket.OutputStream);

							// shutdown the multicast socket and start the tcp connection
							multicastSocket.Dispose();
						} catch {
							if (tcpWriter != null) {
								tcpWriter.Dispose();
								tcpWriter = null;
							}
							if (tcpSocket != null) {
								tcpSocket.Dispose();
								tcpSocket = null;
							}
						}
					}
				}
			} catch (Exception ex) {
				if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) {
					throw;
				}
				Debug.WriteLine(ex.ToString());
			}
		}
开发者ID:88to,项目名称:titanium_mobile,代码行数:40,代码来源:Logger.cs

示例12: sendMail

 public async void sendMail(string strSendTo,string strContent , Boolean hasPicture)
 {
     HostName hostName = new HostName(hostIP);
     StreamSocket socket = new StreamSocket();
     List<string[]> storeList = new List<string[]>();
     try
     {
         await socket.ConnectAsync(hostName, port);
     }
     catch (Exception exception)
     {
         if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
         {
             throw;
         }
     }
     StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Temp");
     StorageFile pic = await folder.GetFileAsync("MyPainter.png");
     IBuffer buffer = await FileIO.ReadBufferAsync(pic);
     DataWriter writer = new DataWriter(socket.OutputStream);
     writer.WriteUInt32(writer.MeasureString(strSendTo));
     writer.WriteString(strSendTo);
     writer.WriteUInt32(writer.MeasureString(strContent));
     writer.WriteString(strContent);
     if (hasPicture)
     {
         writer.WriteUInt32((uint)buffer.Length);
         writer.WriteBuffer(buffer);
     }
     else
     {
         writer.WriteUInt32(0);
         writer.WriteString("");
     }
     await writer.StoreAsync();
     writer.DetachStream();
     writer.Dispose();
     socket.Dispose();
 }
开发者ID:IcePlus,项目名称:KidsPainter,代码行数:39,代码来源:SendMail.cs

示例13: TransferPicture

        private async void TransferPicture(StreamSocket socket)
        {
            // DataWriter erzeugen, um Byte-Umwandlung erledigen zu lassen...
            var writer = new DataWriter(socket.OutputStream);

            // Anzahl der zu übertragenden Bytes übertragen
            writer.WriteInt32(App.PhotoBytesToShare.Length);
            await writer.StoreAsync();

            // Image-Bytes übertragen
            writer.WriteBytes(App.PhotoBytesToShare);
            await writer.StoreAsync();
            await writer.FlushAsync();
            UpdateStatus("Übertragung abgeschlossen.");

            // Ressourcen freigeben
            writer.Dispose();
            socket.Dispose();

            // Beenden der Annahme von Client-Verbindungen
            _listener.Dispose();
        }
开发者ID:GregOnNet,项目名称:WP8BookSamples,代码行数:22,代码来源:ServerPage.xaml.cs

示例14: DownloadUserAvatar

        private async void DownloadUserAvatar(string url, string userid)
        {
            try
            {
                var hc = new HttpClient();
                var response = await hc.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var bitmapByte = await response.Content.ReadAsByteArrayAsync();

                var userFile =
                    await
                    AntaresBaseFolder.Instance.RoamingFolder.CreateFileAsync("Cache\\ProfilePic.jpg",
                                                                             CreationCollisionOption.ReplaceExisting);
                var writeStream = await userFile.OpenAsync(FileAccessMode.ReadWrite);
                var outputStream = writeStream.GetOutputStreamAt(0);
                var dataWriter = new DataWriter(outputStream);

                dataWriter.WriteBytes(bitmapByte);

                await dataWriter.StoreAsync();
                await outputStream.FlushAsync();

                writeStream.Dispose();
                outputStream.Dispose();
                dataWriter.Dispose();

                var userPic = new BitmapImage();
                userPic.SetSource(await userFile.OpenAsync(FileAccessMode.Read));
                UserPic.Source = userPic;
            }
            catch
            {
            }
        }
开发者ID:nghia2080,项目名称:CProject,代码行数:34,代码来源:UserInfoPage.xaml.cs

示例15: TransferPicture_Click

        private async void TransferPicture_Click(object sender, RoutedEventArgs e)
        {
            var selectedPeer = PeersList.SelectedItem as PeerInformation;
            if (selectedPeer == null)
            {
                MessageBox.Show("Bitte Emfängergerät wählen");
                return;
            }

            try
            {
                Status.Text = "Verbinde mit Peer...";
                var peerSocket = await PeerFinder.ConnectAsync(selectedPeer);
                var writer = new DataWriter(peerSocket.OutputStream);

                Status.Text = "Verbunden. Übertrage Bild...";

                // Anzahl der zu übertragenden Bytes übertragen
                writer.WriteInt32(App.ImageBytesToTransfer.Length);
                await writer.StoreAsync();

                // Image-Bytes übertragen
                writer.WriteBytes(App.ImageBytesToTransfer);
                await writer.StoreAsync();
                await writer.FlushAsync();

                // Ressourcen freigeben
                writer.Dispose();
                peerSocket.Dispose();
                Status.Text = "Übertragung abgeschlossen";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: " + ex.Message);
                Status.Text = "Bereit.";
            }
        }
开发者ID:GregOnNet,项目名称:WP8BookSamples,代码行数:37,代码来源:ServerPage.xaml.cs


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