本文整理汇总了C#中Windows.Storage.Streams.DataReader.ReadString方法的典型用法代码示例。如果您正苦于以下问题:C# DataReader.ReadString方法的具体用法?C# DataReader.ReadString怎么用?C# DataReader.ReadString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.DataReader
的用法示例。
在下文中一共展示了DataReader.ReadString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
}
示例2: OnFileOpenButtonClick
async void OnFileOpenButtonClick(object sender, RoutedEventArgs args) {
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".txt");
StorageFile storageFile = await picker.PickSingleFileAsync();
// If user presses Cancel, result is null
if (storageFile == null)
return;
Exception exception = null;
try {
using (IRandomAccessStream stream = await storageFile.OpenReadAsync()) {
using (DataReader dataReader = new DataReader(stream)) {
uint length = (uint)stream.Size;
await dataReader.LoadAsync(length);
txtbox.Text = dataReader.ReadString(length);
}
}
}
catch (Exception exc) {
exception = exc;
}
if (exception != null) {
MessageDialog msgdlg = new MessageDialog(exception.Message, "File Read Error");
await msgdlg.ShowAsync();
}
}
示例3: 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();
}
}
示例4: 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;
}
}
示例5: readHTTPMessage
private async Task<string> readHTTPMessage(DataReader dr)
{
// Make sure we are allowed to return early
dr.InputStreamOptions = InputStreamOptions.Partial;
// This is the value we will return
string ret = "";
// This is the amount of data ready to be read in
uint readyLen;
while (true)
{
// Wait until we've got a kilobyte, or the stream closed
readyLen = await dr.LoadAsync(1024 * 1024);
// Check to see if we actually have any data
if (readyLen > 0)
{
// Read in that string, append it to ret
ret += dr.ReadString(readyLen);
// Check for the "\r\n\r\n" at the end of messages
if (ret.Substring(ret.Length - 4, 4) == "\r\n\r\n")
break;
}
else
{
// If not, the connection is closed!
return ret;
}
}
// Finally, return that string
return ret;
}
示例6: OnOpen
public async void OnOpen()
{
try
{
var picker = new FileOpenPicker()
{
SuggestedStartLocation = PickerLocationId.DocumentsLibrary
};
picker.FileTypeFilter.Add(".txt");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
IRandomAccessStreamWithContentType stream = await file.OpenReadAsync();
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
text1.Text = reader.ReadString((uint)stream.Size);
}
}
}
catch (Exception ex)
{
var dlg = new MessageDialog(ex.Message, "Error");
await dlg.ShowAsync();
}
}
示例7: 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);
};
};
};
}
示例8: ReadBlock_Click
private async void ReadBlock_Click(object sender, RoutedEventArgs e)
{
var fx2Device = DeviceList.Current.GetSelectedDevice();
if (fx2Device == null)
{
rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
return;
}
var button = (Button)sender;
button.IsEnabled = false;
var dataReader = new DataReader(fx2Device.InputStream);
// load the data reader from the stream. For purposes of this
// sample, assume all messages read are < 64 bytes
int counter = readCounter++;
LogMessage("Read {0} begin", counter);
await dataReader.LoadAsync(64);
// Get the message string out of the buffer
var message = dataReader.ReadString(dataReader.UnconsumedBufferLength);
LogMessage("Read {0} end: {1}", counter, message);
button.IsEnabled = true;
}
示例9: 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());
}
示例10: 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;
}
示例11: LoadFrom
public static async Task<bool> LoadFrom ( ObservableCollection<RecentData> datas )
{
try
{
StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync ( "data.dat" );
FileRandomAccessStream stream = await sf.OpenAsync ( FileAccessMode.Read ) as FileRandomAccessStream;
DataReader dr = new DataReader ( stream );
dr.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
dr.ByteOrder = ByteOrder.LittleEndian;
await dr.LoadAsync ( ( uint ) stream.Size );
int len = dr.ReadInt32 ();
for ( int i = 0; i < len; i++ )
{
RecentData data = new RecentData ();
uint srclen = dr.ReadUInt32 ();
data.Source = dr.ReadString ( srclen );
data.SourceIndex = dr.ReadInt32 ();
data.TargetIndex = dr.ReadInt32 ();
datas.Add ( data );
}
stream.Dispose ();
}
catch { return false; }
return true;
}
示例12: LoadSettings
public async void LoadSettings()
{
try
{
string contents;
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textFile = await localFolder.GetFileAsync("settingV2");
using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
{
using (DataReader textReader = new DataReader(textStream))
{
uint textLength = (uint)textStream.Size;
await textReader.LoadAsync(textLength);
contents = textReader.ReadString(textLength);
}
}
string[] lines = contents.Split('\n');
bool.TryParse(lines[0], out AutoJoinChat);
bool.TryParse(lines[1], out LockLandscape);
bool.TryParse(lines[2], out LiveTilesEnabled);
}
catch { }
}
示例13: 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();
}
}
示例14: OpenGraphFile_Click
async private void OpenGraphFile_Click(object sender, RoutedEventArgs e)
{
var picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".txt");
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SettingsIdentifier = "GraphPicker";
picker.CommitButtonText = "Select Files";
var selectedFile = await picker.PickSingleFileAsync();
using (IRandomAccessStream stream = await selectedFile.OpenReadAsync())
{
using (DataReader reader = new DataReader(stream))
{
uint length = (uint)stream.Size;
await reader.LoadAsync(length);
string[] s = reader.ReadString(length).Split('\r');
string[][] str = new string[s.Length][];
for (int i = 0; i < s.Length; i++)
str[i] = s[i].Replace('\n', ' ').Split(' ');
int n = int.Parse(s[0]);
int[,] adjMatrix = new int[n, n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
adjMatrix[i, j] = int.Parse(str[i + 1][j + 1]);
adjMatrix[0, 0] += 0;
graph = new Graph(adjMatrix, n);
}
}
}
示例15: OnForegroundSocketClicked
private async void OnForegroundSocketClicked(object sender, RoutedEventArgs e)
{
socket = new StreamSocket();
HostName host = new HostName("localhost");
try
{
await socket.ConnectAsync(host, "1983");
isConnected = true;
while (isConnected)
{
try
{
DataReader reader;
using (reader = new DataReader(socket.InputStream))
{
// Set the DataReader to only wait for available data (so that we don't have to know the data size)
reader.InputStreamOptions = InputStreamOptions.Partial;
// The encoding and byte order need to match the settings of the writer we previously used.
reader.UnicodeEncoding = UnicodeEncoding.Utf8;
reader.ByteOrder = ByteOrder.LittleEndian;
// Send the contents of the writer to the backing stream.
// Get the size of the buffer that has not been read.
await reader.LoadAsync(256);
// Keep reading until we consume the complete stream.
while (reader.UnconsumedBufferLength > 0)
{
string readString = reader.ReadString(reader.UnconsumedBufferLength);
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
messages.Add(readString);
});
Debug.WriteLine(readString);
await reader.LoadAsync(256);
}
reader.DetachStream();
}
}
catch (Exception exc)
{
MessageDialog dialog = new MessageDialog("Error reading the data");
await dialog.ShowAsync();
}
}
}
catch (Exception exc)
{
MessageDialog dialog = new MessageDialog("Error connecting to the socket");
await dialog.ShowAsync();
}
}