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


C# DataReader.Dispose方法代码示例

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


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

示例1: ReadAllText

 public void ReadAllText(string filename, Action<string> completed)
 {
     StorageFolder localFolder = 
                     ApplicationData.Current.LocalFolder;
     IAsyncOperation<StorageFile> createOp = 
                     localFolder.GetFileAsync(filename);
     createOp.Completed = (asyncInfo1, asyncStatus1) =>
     {
         IStorageFile storageFile = asyncInfo1.GetResults();
         IAsyncOperation<IRandomAccessStreamWithContentType> 
             openOp = storageFile.OpenReadAsync();
         openOp.Completed = (asyncInfo2, asyncStatus2) =>
         {
             IRandomAccessStream stream = asyncInfo2.GetResults();
             DataReader dataReader = new DataReader(stream);
             uint length = (uint)stream.Size;
             DataReaderLoadOperation loadOp = 
                                 dataReader.LoadAsync(length);
             loadOp.Completed = (asyncInfo3, asyncStatus3) =>
             {
                 string text = dataReader.ReadString(length);
                 dataReader.Dispose();
                 completed(text);
             };
         };
     };
 }
开发者ID:karanga,项目名称:xamarin-forms-book-preview,代码行数:27,代码来源:FileHelper.cs

示例2: ReadFromFileAsync

        /// <summary>
        /// Read string content from file.
        /// </summary>
        /// <param name="path">Location of file, separate by //.</param>
        /// <param name="rootFolder"> </param>
        /// <returns>Content of file.</returns>
        public async Task<string> ReadFromFileAsync(string path, StorageFolder rootFolder = null)
        {
            if (path == null)
            {
                return null;
            }

            try
            {
                var file = await GetFileToReadAsync(path, rootFolder);

                if (file == null)
                {
                    return null;
                }

                var readStream = await file.OpenAsync(FileAccessMode.Read);

                var inputStream = readStream.GetInputStreamAt(0);
                var dataReader = new DataReader(inputStream);

                var numBytesLoaded = await dataReader.LoadAsync((uint)readStream.Size);
                var content = dataReader.ReadString(numBytesLoaded);
                dataReader.DetachStream();
                dataReader.Dispose();
                inputStream.Dispose();
                readStream.Dispose();

                return content;
            }
            catch
            {
                return null;
            }
        }
开发者ID:nghia2080,项目名称:CProject,代码行数:41,代码来源:IOStream.cs

示例3: ReceiveImage

        private async void ReceiveImage(StreamSocket socket)
        {
            // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
            var reader = new DataReader(socket.InputStream);

            // Anzahl der Bytes abrufen, aus denen das Bild besteht
            // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
            await reader.LoadAsync(4);
            int imageSize = reader.ReadInt32();

            // Bytearray des Bildes laden
            await reader.LoadAsync((uint)imageSize);
            byte[] imageBytes = new byte[imageSize];
            reader.ReadBytes(imageBytes);
            
            // Bytearray in Stream laden und anzeigen
            using (var ms = new MemoryStream(imageBytes))
            {
                var image = new BitmapImage();
                image.SetSource(ms);

                ReceivedImage.Source = image;
            }
            Status.Text = "Bild empfangen.";

            // Ressourcen freigeben
            reader.Dispose();
            socket.Dispose();
        }
开发者ID:GregOnNet,项目名称:WP8BookSamples,代码行数:29,代码来源:ClientPage.xaml.cs

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

示例5: recieveData

        async private void recieveData()
        {
            StreamSocketListener listener = new StreamSocketListener();
            DataReader dr = new DataReader(newSocket.InputStream);
            dr.InputStreamOptions = InputStreamOptions.Partial;
            string msg = null;
            try
            {
                var count = await dr.LoadAsync(8192);
                if (count > 0)
                    msg = dr.ReadString(count);
            }
            catch { }
            dr.DetachStream();
            dr.Dispose();

            try
            {
                pdu2 = new PDU(msg);
                Execution temp = pdu2.Data.ToObject(typeof(Execution));
                _stepCollection.Clear();
                foreach (Step steps in temp.CurrentSequence.StepList)
                {
                    _stepCollection.Add(steps);
                }
            }

            catch (Exception e) { }
            Execution temp2 = pdu2.Data.ToObject(typeof(Execution));
            if (temp2.State == Execution.ExecutionStates.FINISHED || temp2.State == Execution.ExecutionStates.TERMINATED)
            {
                PDU pdu3 = new PDU(){
                    MessageID = (int)CommandMessageID.ResetTS,
                    MessageDescription = "Server please, reset TS",
                    MessageType = "Command",
                    Source = "Demo.Client",
                    Data = new JObject()
                };
                sendData(pdu3);
            } else { recieveData(); }
            
        }
开发者ID:Chrislaos,项目名称:MetroSocket2,代码行数:42,代码来源:SequencePage.xaml.cs

示例6: ReceiveImage

        private async void ReceiveImage(PeerInformation peer)
        {
            try
            {
                Status.Text = "Verbinde mit Peer...";
                StreamSocket peerSocket = await PeerFinder.ConnectAsync(peer);
                Status.Text = "Verbunden. Empfange Daten...";

                // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
                var reader = new DataReader(peerSocket.InputStream);

                // Anzahl der Bytes abrufen, aus denen das Bild besteht
                // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
                await reader.LoadAsync(4);
                int imageSize = reader.ReadInt32();

                // Bytearray des Bildes laden
                await reader.LoadAsync((uint)imageSize);
                byte[] imageBytes = new byte[imageSize];
                reader.ReadBytes(imageBytes);

                // Bytearray in Stream laden und anzeigen
                using (var ms = new MemoryStream(imageBytes))
                {
                    var image = new BitmapImage();
                    image.SetSource(ms);

                    ReceivedImage.Source = image;
                }
                Status.Text = "Bild empfangen.";

                // Ressourcen freigeben
                reader.Dispose();
                peerSocket.Dispose();

                // Wieder Verbindungen akzeptieren
                PeerFinder.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: " + ex.Message);
                Status.Text = "Bereit.";
            }
        }
开发者ID:GregOnNet,项目名称:WP8BookSamples,代码行数:44,代码来源:ClientPage.xaml.cs

示例7: Run

        public override void Run()
        {
            #if WINRT
            StorageFile file = Package.Current.InstalledLocation.GetFileAsync(_path).AsTask().Result;
            using(var raStream = file.OpenReadAsync().AsTask().Result)
            {
                byte[] blob = new byte[CHUNK_SIZE];

                while (IsRunning && raStream.CanRead)
                {
                    DataReader reader = new DataReader(raStream.GetInputStreamAt(0));
                    reader.InputStreamOptions = InputStreamOptions.Partial;
                    try
                    {
                        reader.LoadAsync((uint)blob.Length).AsTask().Wait();
                        int bytesRead = 0;
                        while (reader.UnconsumedBufferLength > 0)
                        {
                            blob[bytesRead++] = reader.ReadByte();
                        }

                        if (bytesRead > 0)
                        {
                            HandleData(blob, bytesRead);
                        }
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        reader.DetachStream();
                        reader.Dispose();
                    }

                    if (raStream.Position >= raStream.Size)
                    {
                        Terminate();
                        break;
                    }

                    Task.Delay(INTERVAL).Wait();
                }
            }
            #else
            byte [] blob = new byte[CHUNK_SIZE];

            while(IsRunning && _fileStream.CanRead)
            {
                int read = _fileStream.Read(blob, 0, CHUNK_SIZE);

                if( read > 0 )
                {
                    HandleData(blob, read);
                }

                if(_fileStream.CanSeek && _fileStream.Position >= _fileStream.Length)
                {
                    Terminate();
                    break;
                }

                Thread.Sleep(INTERVAL);
            }
            #endif
        }
开发者ID:visual14ph,项目名称:f1livetiming,代码行数:66,代码来源:FileCapDriver.cs

示例8: DoNextRead

        private void DoNextRead(byte[] blob)
        {
            DataReader reader = new DataReader(_socket.InputStream);
            reader.InputStreamOptions = InputStreamOptions.Partial;

            var task = Task.Run(() =>
            {
                try
                {
                    reader.LoadAsync((uint)blob.Length).AsTask().Wait();
                    uint bytesRead = 0;
                    while(reader.UnconsumedBufferLength > 0)
                    {
                        blob[bytesRead++] = reader.ReadByte();
                    }

                    if(bytesRead > 0)
                    {
                        OnReceive(blob, bytesRead);
                    }
                }
                catch(Exception)
                {
                }
                finally
                {
                    reader.DetachStream();
                    reader.Dispose();
                }
            });
        }
开发者ID:visual14ph,项目名称:f1livetiming,代码行数:31,代码来源:W8ConnectionDriver.cs

示例9: _tcp_ConnectionReceived

        private async void _tcp_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                scan_transfer_speed();
                
                _datareader = new DataReader(args.Socket.InputStream);
                _datareader.InputStreamOptions = InputStreamOptions.Partial;

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting);

                IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite);
                IOutputStream filewriter = filestream.GetOutputStreamAt(0);

                _datawriter = new DataWriter(filewriter);

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

                    _transferspeed += _length;

                    if (_write)
                    {
                        _transferspeed /= 1024;
                        _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s");
                        this.callback.on_transfer_speed_change(_message, this.results);
                        this.main_view.text_to_logs(_message.Replace("\t", " "));

                        _transferspeed = 0;
                        _write = false;
                    }

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

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

                _timer.Cancel();

                _transferspeed /= 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _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", " "));

                _tcplistener.Dispose();                

                _stopwatch.Stop();

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

示例10: send_file

        public override async void send_file(String devicename, String bluid, int not)
        {
            try {
                _stopwatch.Start();

                PeerFinder.AllowBluetooth = true;
                PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{" + bluid + "}";

                var peers = await PeerFinder.FindAllPeersAsync();

                foreach (var p in peers)
                {
                    if (p.DisplayName.Equals(devicename))
                    {
                        _peer_info = p;
                        break;
                    }
                }

                _bluetooth_client = new StreamSocket();

                if (_peer_info.ServiceName.Equals(""))
                {
                    await _bluetooth_client.ConnectAsync(_peer_info.HostName, "{" + bluid + "}");
                }
                else
                {
                    await _bluetooth_client.ConnectAsync(_peer_info.HostName, _peer_info.ServiceName);
                }

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

                IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync();

                _length = (uint)filestream.Size;

                _ibuffer = new Windows.Storage.Streams.Buffer(_length);

                _datareader = new DataReader(filestream);
                await _datareader.LoadAsync(_length);
                _ibuffer = _datareader.ReadBuffer(_length);

                _datawriter = new DataWriter(_bluetooth_client.OutputStream);
                _datawriter.WriteBuffer(_ibuffer);
                await _datawriter.StoreAsync();

                filestream.Dispose();
                _datareader.Dispose();
                _datawriter.Dispose();
                               
                _datareader = new DataReader(_bluetooth_client.InputStream);
                _datareader.InputStreamOptions = InputStreamOptions.Partial;

                scan_received_acks();

                while (true)
                {
                    uint count = await _datareader.LoadAsync(4);
                    byte[] ack = new byte[count];

                    _datareader.ReadBytes(ack);

                    _counter_all_acks += BitConverter.ToInt32(ack, 0);

                    if ((uint)_counter_all_acks == _length) break;
                }

                _datareader.Dispose();
                _bluetooth_client.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", " "));

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

示例11: OnRead

        private async void OnRead(Object sender, RoutedEventArgs e)
        {
            StorageFolder local = ApplicationData.Current.LocalFolder;

            StorageFile file = await local.GetFileAsync("demo.dat");
            if(file != null)
            {
                string strres = "读到的内容:\n";
                using(IRandomAccessStream stream = await file.OpenReadAsync())
                {
                    DataReader dr = new DataReader(stream);
                    dr.UnicodeEncoding = UnicodeEncoding.Utf8;
                    await dr.LoadAsync((uint)stream.Size);
                    bool b = dr.ReadBoolean();
                    strres += b.ToString() + "\n";
                    DateTimeOffset dt = dr.ReadDateTime();
                    strres += dt.ToString("yyyy-M-d") + "\n";
                    uint len = dr.ReadUInt32();
                    if(len > 0)
                    {
                        strres += dr.ReadString(len);
                    }
                    dr.Dispose();
                }
                tbResult.Text = strres;
            }
        }
开发者ID:forehalo,项目名称:UWP-dev,代码行数:27,代码来源:_DataWriter.xaml.cs

示例12: Load

        public void Load(string filename)
        {

#if !WINDOWS_PHONE // iOS and Android

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

            // Break string into Title and Text.
            int index = text.IndexOf('\n');
            this.Title = text.Substring(0, index);
            this.Text = text.Substring(index + 1);

#else // Windows Phone

            StorageFolder localFolder = 
                                ApplicationData.Current.LocalFolder;
            IAsyncOperation<StorageFile> createOp = 
                                localFolder.GetFileAsync(filename);
            createOp.Completed = (asyncInfo1, asyncStatus1) =>
            {
                IStorageFile storageFile = asyncInfo1.GetResults();
                IAsyncOperation<IRandomAccessStreamWithContentType> 
                        openOp = storageFile.OpenReadAsync();
                openOp.Completed = (asyncInfo2, asyncStatus2) =>
                {
                    IRandomAccessStream stream = asyncInfo2.GetResults();
                    DataReader dataReader = new DataReader(stream);
                    uint length = (uint)stream.Size;
                    DataReaderLoadOperation loadOp = 
                            dataReader.LoadAsync(length);
                    loadOp.Completed = (asyncInfo3, asyncStatus3) =>
                    {
                        string text = dataReader.ReadString(length);
                        dataReader.Dispose();

                        // Break string into Title and Text.
                        int index = text.IndexOf('\n');
                        this.Title = text.Substring(0, index);
                        this.Text = text.Substring(index + 1);
                    };
                };
            };
     
#endif

        }
开发者ID:karanga,项目名称:xamarin-forms-book-preview,代码行数:49,代码来源:Note.cs

示例13: PeerFinder_StartReader

 async void PeerFinder_StartReader(DataReader socketReader)
 {
     try
     {
         uint bytesRead = await socketReader.LoadAsync(sizeof(uint));
         if (bytesRead > 0)
         {
             uint strLength = (uint)socketReader.ReadUInt32();
             bytesRead = await socketReader.LoadAsync(strLength);
             if (bytesRead > 0)
             {
                 String message = socketReader.ReadString(strLength);
                 this.NotifyUser("Got message: " + message, NotifyType.PeerMessage);
                 PeerFinder_StartReader(socketReader); // Start another reader
             }
             else
             {
                 SocketError("The remote side closed the socket");
                 socketReader.Dispose();
             }
         }
         else
         {
             SocketError("The remote side closed the socket");
             socketReader.Dispose();
         }
     }
     catch (Exception e)
     {
         if (!_socketClosed)
         {
             SocketError("Reading from socket failed: " + e.Message);
         }
         socketReader.Dispose();
     }
 }
开发者ID:paraneye,项目名称:WinApp,代码行数:36,代码来源:ProximityReadHandler.cs

示例14: recieveData

        async private void recieveData()
        {
            StreamSocketListener listener = new StreamSocketListener();
            DataReader dr = new DataReader(socket.InputStream);
            dr.InputStreamOptions = InputStreamOptions.Partial;
            string msg = null;
            var count = await dr.LoadAsync(4096);

            if (count > 0)
                msg = dr.ReadString(count);
            recievedMessage.Text = msg;

            dr.DetachStream();
            dr.Dispose();

            try
            {
                PDU pdu2 = new PDU(msg);
                Procedure temp = pdu2.Data.ToObject(typeof(Procedure));
                _kakecollection.Add(new kakeclass { Name = temp.Name, Description = temp.Description, Date = temp.Date });
            }
            catch (Exception e) { recievedMessage.Text = "Failed to cast incomming message to usable type: PDU"; }

            try
            {
                listener.ConnectionReceived += listener_ConnectionReceived;
                await listener.BindServiceNameAsync(socketString);
                

            }
            catch (Exception e) { recievedMessage.Text = e.ToString(); }

        }
开发者ID:Chrislaos,项目名称:TheSocketThing,代码行数:33,代码来源:MainPage.xaml.cs

示例15: StartReceiveData

        async void StartReceiveData(DataReader socketReader)
        {
            try
            {
                uint bytesRead = await socketReader.LoadAsync(sizeof(uint));
                if (bytesRead > 0)
                {
                    uint strLength = (uint)socketReader.ReadUInt32();
                    bytesRead = await socketReader.LoadAsync(strLength);
                    if (bytesRead > 0)
                    {
                        byte[] bytesIn = new byte[bytesRead];

                        Debug.WriteLine("ReadBytes");
                        socketReader.ReadBytes(bytesIn);
                        Debug.WriteLine("ReadBytes End");

                       
                        if (DataReceived != null)
                        {
                            DataReceivedEventArgs args = new DataReceivedEventArgs();
                            args.Bytes = bytesIn;
                            DataReceived(this, args);
                        }

                        StartReceiveData(socketReader); // Start another reader
                    }
                    else
                    {
                        SocketError("The remote side closed the socket");
                        socketReader.Dispose();
                        UpdateConnectionStatus(ConnectionStatus.Disconnected);
                    }
                }
                else
                {
                    SocketError("The remote side closed the socket");
                    socketReader.Dispose();
                    UpdateConnectionStatus(ConnectionStatus.Disconnected);
                }
            }
            catch (Exception e)
            {
                if (!_socketClosed)
                {
                    SocketError("Reading from socket failed: " + e.Message);
                }
                socketReader.Dispose();
            }
        }
开发者ID:kamaelyoung,项目名称:MultiPlatform,代码行数:50,代码来源:SimplePeerConnector.cs


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