• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Streams.DataReader类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



DataReader类属于Windows.Storage.Streams命名空间,在下文中一共展示了DataReader类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: OnDataReadCompletion

 public void OnDataReadCompletion(UInt32 bytesRead, DataReader readPacket)
 {
    
     if (readPacket == null)
     {
         Debug.WriteLine("DataReader is null");
     }
     else if (readPacket.UnconsumedBufferLength != 0)
     {
         Byte[] numArray = new Byte[bytesRead];
         readPacket.ReadBytes(numArray);
         Response response = parser.processRawBytes(numArray);
         if (response != null)
         {
             DispatchResponseThreadSafe(response);
         }
         PostSocketRead(16);
     }
     else
     {
         Debug.WriteLine("Received zero bytes from the socket. Server must have closed the connection.");
         Debug.WriteLine("Try disconnecting and reconnecting to the server");
     }
     
 }
开发者ID:xesf,项目名称:Sphero-WinPhone8-SDK,代码行数:25,代码来源:RobotSession.cs


示例2: getButton_Click

        private async void getButton_Click(object sender, RoutedEventArgs e)
        {
            // This constructs a string of the form "http://www.google.com:80/"
            HttpWebRequest request = WebRequest.CreateHttp( "http://" + this.hostnameText.Text + ":" + this.portText.Text + this.resourceText.Text);

            try
            {
                using (var response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null))
                {
                    // Create a datareader off of our response stream
                    DataReader dr = new DataReader(response.GetResponseStream().AsInputStream());

                    // Throw the HTTP text into our textOutput
                    this.textOutput.Text = await readHTTPMessage(dr);

                    // As this was a successful request, make the text green:
                    this.textOutput.Foreground = new SolidColorBrush(Color.FromArgb(255, 128, 255, 128));
                }
            }
            catch (Exception ex)
            {
                // We ran into some kind of problem; output it to the user!
                this.textOutput.Text = "Error: " + ex.Message;
                this.textOutput.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 128, 128));
            }
        }
开发者ID:EE590-Spring2014,项目名称:Materials,代码行数:26,代码来源:MainPage.xaml.cs


示例3: save_Video

        private async void save_Video(object sender, RoutedEventArgs e)
        {
            // Adding try catch block in case of occurence of an exception
            try
            {
                // Creating object of FileSavePicker and adding few values to the properties of the object.
                FileSavePicker fs = new FileSavePicker();
                fs.FileTypeChoices.Add("Video", new List<string>() { ".mp4",".3gp" });
                fs.DefaultFileExtension = ".mp4";
                fs.SuggestedFileName = "Video" + DateTime.Today.ToString();
                fs.SuggestedStartLocation = PickerLocationId.VideosLibrary;

                // Using storagefile object defined earlier in above method to save the file using filesavepicker.
                fs.SuggestedSaveFile = sf;

                // Saving the file
                var s = await fs.PickSaveFileAsync();
                if (s != null)
                {
                    using (var dataReader = new DataReader(rs.GetInputStreamAt(0)))
                    {
                        await dataReader.LoadAsync((uint)rs.Size);
                        byte[] buffer = new byte[(int)rs.Size];
                        dataReader.ReadBytes(buffer);
                        await FileIO.WriteBytesAsync(s, buffer);
                    }
                }
            }
            catch (Exception ex)
            {
                var messageDialog = new MessageDialog("Something went wrong.");
                await messageDialog.ShowAsync();
            }
        }
开发者ID:sarthakbhol,项目名称:Windows10AppSamples,代码行数:34,代码来源:MainPage.xaml.cs


示例4: WinRtTransferHandler

		public WinRtTransferHandler(StreamSocket socket)
		{
			if (socket == null) throw new ArgumentNullException("socket");

			_reader = new DataReader(socket.InputStream);
			_writer = new DataWriter(socket.OutputStream);
		}
开发者ID:ppetrov,项目名称:iFSA.Service,代码行数:7,代码来源:WinRtTransferHandler.cs


示例5: SocketHandler

        public SocketHandler(StreamSocket socket)
        {
            this.socket = socket;

            this.reader = new DataReader(this.socket.InputStream);
            this.writer = new DataWriter(this.socket.OutputStream);
        }
开发者ID:philipp2500,项目名称:Remote-Content-Show,代码行数:7,代码来源:SocketHandler.cs


示例6: ReadFromStreamButton_Click

 private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
 {
     StorageFile file = rootPage.sampleFile;
     if (file != null)
     {
         try
         {
             using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
             {
                 using (DataReader dataReader = new DataReader(readStream))
                 {
                     UInt64 size = readStream.Size;
                     if (size <= UInt32.MaxValue)
                     {
                         UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
                         string fileContent = dataReader.ReadString(numBytesLoaded);
                         rootPage.NotifyUser(String.Format("The following text was read from '{0}' using a stream:{1}{2}", file.Name, Environment.NewLine, fileContent), NotifyType.StatusMessage);
                     }
                     else
                     {
                         rootPage.NotifyUser(String.Format("File {0} is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.", file.Name), NotifyType.ErrorMessage);
                     }
                 }
             }
         }
         catch (FileNotFoundException)
         {
             rootPage.NotifyUserFileNotExist();
         }
     }
     else
     {
         rootPage.NotifyUserFileNotExist();
     }
 }
开发者ID:ckc,项目名称:WinApp,代码行数:35,代码来源:Scenario5_WriteAndReadAFileUsingAStream.xaml.cs


示例7: AsRandomAccessStreamAsync

        public async static Task<IRandomAccessStream> AsRandomAccessStreamAsync(this Stream stream)
        {
            Stream streamToConvert = null;

            if (!stream.CanRead)
            {
                throw new Exception("Cannot read the source stream-");
            }
            if (!stream.CanSeek)
            {
                MemoryStream memoryStream = new MemoryStream();
                await stream.CopyToAsync(memoryStream);
                streamToConvert = memoryStream;
            }
            else
            {
                streamToConvert = stream;
            }

            DataReader dataReader = new DataReader(streamToConvert.AsInputStream());
            streamToConvert.Position = 0;
            await dataReader.LoadAsync((uint)streamToConvert.Length);
            IBuffer buffer = dataReader.ReadBuffer((uint)streamToConvert.Length);

            InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
            IOutputStream outputstream = randomAccessStream.GetOutputStreamAt(0);
            await outputstream.WriteAsync(buffer);
            await outputstream.FlushAsync();

            return randomAccessStream;
        }
开发者ID:uwe-e,项目名称:BSE.Tunes,代码行数:31,代码来源:StreamExtensions.cs


示例8: Read

        private async void Read()
        {
            _reader = new DataReader(_socket.InputStream);
            try
            {
                while (true)
                {
                    uint sizeFieldCount = await _reader.LoadAsync(sizeof(uint));
                    //if desconneted
                    if (sizeFieldCount != sizeof(uint))
                        return;

                    uint stringLenght = _reader.ReadUInt32();
                    uint actualStringLength = await _reader.LoadAsync(stringLenght);
                    //if desconneted
                    if (stringLenght != actualStringLength)
                        return;
                    if (OnDataRecived != null)
                        OnDataRecived(_reader.ReadString(actualStringLength));
                }

            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError(ex.Message);
            }
        }
开发者ID:lillo42,项目名称:IoT,代码行数:28,代码来源:SocketClient.cs


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


示例10: ReceiveMessages

        /// <summary>
        /// Receive message through bluetooth.
        /// </summary>
        protected async Task<byte[]> ReceiveMessages(DataReader dataReader)
        {
            try
            {
                
                // Read the message. 
                List<Byte> all = new List<byte>();

                while (true)
                {
                    var bytesAvailable = await dataReader.LoadAsync(1000);
                    var byteArray = new byte[bytesAvailable];
                    dataReader.ReadBytes(byteArray);
                    if (byteArray.Length > 0 && byteArray[0] != byte.MinValue)
                    {
                        if (OnDataRead != null) OnDataRead(byteArray);
                        return byteArray;
                    }

                    Thread.Sleep(100);
                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return null;
        }
开发者ID:nothingmn,项目名称:zVirtualScenes-Client,代码行数:32,代码来源:BaseChannel.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: OnConnection

        private static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            ConnectionStatus = ConnectionStatus.Connected;
            DataReader reader = new DataReader(args.Socket.InputStream);
            try
            {
                while (true)
                {
                    uint sizeFieldCount = await reader.LoadAsync(sizeof (uint));
                    if (sizeFieldCount != sizeof (uint))
                    {
                        return;
                    }
                    
                    uint stringLength = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);
                    if (stringLength != actualStringLength)
                    {
                        return;
                    }

                    Message = reader.ReadString(actualStringLength);
                }
            }
            catch (Exception e)
            {
                ConnectionStatus = ConnectionStatus.Failed;
                //TODO:send a connection status message with error
            }
        }
开发者ID:95strat,项目名称:GoPiGoWin10,代码行数:30,代码来源:SocketConnection.cs


示例13: ConnectAsync

        internal async Task ConnectAsync(
            HostName hostName,
            string serviceName,
            string user,
            string password)
        {
            if (controlStreamSocket != null)
            {
                throw new InvalidOperationException("Control connection already started.");
            }

            this.hostName = hostName;

            controlStreamSocket = new StreamSocket();
            await controlStreamSocket.ConnectAsync(hostName, serviceName);

            reader = new DataReader(controlStreamSocket.InputStream);
            reader.InputStreamOptions = InputStreamOptions.Partial;

            writer = new DataWriter(controlStreamSocket.OutputStream);

            readCommands = new List<string>();
            loadCompleteEvent = new AutoResetEvent(false);
            readTask = InfiniteReadAsync();

            FtpResponse response;
            response = await GetResponseAsync();
            VerifyResponse(response, 220);

            response = await UserAsync(user);
            VerifyResponse(response, 331);

            response = await PassAsync(password);
            VerifyResponse(response, 230);
        }
开发者ID:kiewic,项目名称:FtpClient,代码行数:35,代码来源:FtpClient.cs


示例14: DeserializeAppData

        public static async Task<AppModel> DeserializeAppData()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            AppModel appModel = null;
            try
            {
                // Getting JSON from file if it exists, or file not found exception if it does not  
                StorageFile textFile = await localFolder.GetFileAsync("app.json");
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    // Read text stream     
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        //get size                       
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        // read it                    
                        string jsonContents = textReader.ReadString(textLength);
                        // deserialize back to our product!  
                        appModel = JsonConvert.DeserializeObject<AppModel>(jsonContents);
                       
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return appModel;
        }
开发者ID:rloreto,项目名称:qbapp,代码行数:31,代码来源:Utils.cs


示例15: Read

        public async Task<IEnumerable<Event>> Read() 
        {
            List<Event> events = null;
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            try
            {
                StorageFile textFile = await localFolder.GetFileAsync("SavedContent");
                events = new List<Event>();
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        string jsonContents = textReader.ReadString(textLength);
                        events = JsonConvert.DeserializeObject<IList<Event>>(jsonContents) as List<Event>;
                    }
                    return events;
                }
            }
            catch (Exception ex)
            {
                return null;
            }

        }
开发者ID:mjtpena,项目名称:Aevents,代码行数:26,代码来源:LocalStorageService.cs


示例16: Listener_ConnectionReceived

    private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
    {
        socket = args.Socket;
        var dr = new DataReader(socket.InputStream);

        /// GET ヘッダを取り出し
        StringBuilder request = new StringBuilder();
        uint BufferSize = 1024;
        using (IInputStream input = socket.InputStream)
        {
            byte[] data = new byte[BufferSize];
            IBuffer buffer = data.AsBuffer();
            uint dataRead = BufferSize;
            while (dataRead == BufferSize)
            {
                await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
                request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                dataRead = buffer.Length;
            }
        }
        // GET method を取り出し
        string requestMethod = request.ToString().Split('\n')[0];
        string[] requestParts = requestMethod.Split(' ');
        var text = requestParts[1];

        /// GETコマンドの受信イベント
        if (this.OnReceived != null)
        {
            OnReceived(text);
        }
    }
开发者ID:moonmile,项目名称:winiot-samples,代码行数:31,代码来源:SimpleWebServer.cs


示例17: Read

 private async Task<RfidReaderResult> Read()
 {
     RfidReaderResult retvalue = new RfidReaderResult();
     var dataReader = new DataReader(_rfidReader.InputStream);
     try
     {
         SetStatus("Awaiting Data from RFID Reader");
         var numBytesRecvd = await dataReader.LoadAsync(1024);
         retvalue.Result = new byte[numBytesRecvd];
         if (numBytesRecvd > 0)
         {
             SetStatus("Data successfully read from RFID Reader");
             dataReader.ReadBytes(retvalue.Result);
             retvalue.IsSuccessful = true;
             retvalue.Message = "Data successfully read from RFID Reader";
         }
     }
     catch (Exception ex)
     {
         retvalue.IsSuccessful = false;
         retvalue.Message = ex.Message;
     }
     finally
     {
         if (dataReader != null)
         {
             dataReader.DetachStream();
             dataReader = null;
         }
     }
     return retvalue;
 }
开发者ID:codingbandit,项目名称:CottonwoodSerialTester,代码行数:32,代码来源:MainPage.xaml.cs


示例18: Connect

        public async Task<bool> Connect()
        {
            if (_connected) return false;
            var hostname = new HostName("62.4.24.188");
            //var hostname = new HostName("192.168.1.12");
            CancellationTokenSource cts = new CancellationTokenSource();
            try
            {
                cts.CancelAfter(5000);
                await _clientSocket.ConnectAsync(hostname, "4242").AsTask(cts.Token);
            }
            catch (TaskCanceledException)
            {
                _connected = false;
                return false;
            }
            _connected = true;
            _dataReader = new DataReader(_clientSocket.InputStream)
            {
                InputStreamOptions = InputStreamOptions.Partial
            };
            ReadData();
            return true;

        }
开发者ID:patel-pragnesh,项目名称:PowerMonitor,代码行数:25,代码来源:Socket.cs


示例19: ReadFromStreamButton_Click

 private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         rootPage.ResetScenarioOutput(OutputTextBlock);
         StorageFile file = rootPage.sampleFile;
         if (file != null)
         {
             using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
             {
                 using (DataReader dataReader = new DataReader(readStream))
                 {
                     UInt64 size = readStream.Size;
                     if (size <= UInt32.MaxValue)
                     {
                         UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
                         string fileContent = dataReader.ReadString(numBytesLoaded);
                         OutputTextBlock.Text = "The following text was read from '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + fileContent;
                     }
                     else
                     {
                         OutputTextBlock.Text = "File " + file.Name + " is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.";
                     }
                 }
             }
         }
     }
     catch (FileNotFoundException)
     {
         rootPage.NotifyUserFileNotExist();
     }
 }
开发者ID:mac10688,项目名称:PublicWorkspace,代码行数:32,代码来源:Scenario4.xaml.cs


示例20: LoadAsync

        public static async Task<DiscoveryServiceCache> LoadAsync()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            try
            {
                _lock.EnterReadLock();
                StorageFile textFile = await localFolder.GetFileAsync(FileName);

                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        uint textLength = (uint)textStream.Size;

                        await textReader.LoadAsync(textLength);
                        return Load(textReader);
                    }
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                _lock.ExitReadLock();
            }

            return null;
        }
开发者ID:delacruzjayveejoshua920,项目名称:ICNG-App-for-Windows-8.1-and-Windows-Phone-8.1-,代码行数:30,代码来源:DiscoveryServiceCache.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Streams.DataWriter类代码示例发布时间:2022-05-26
下一篇:
C# Pickers.FileSavePicker类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap