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


C# Streams.DataReader类代码示例

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


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


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