本文整理汇总了C#中Windows.Storage.Streams.DataReader.DetachStream方法的典型用法代码示例。如果您正苦于以下问题:C# DataReader.DetachStream方法的具体用法?C# DataReader.DetachStream怎么用?C# DataReader.DetachStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.DataReader
的用法示例。
在下文中一共展示了DataReader.DetachStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
示例2: 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());
}
示例3: 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;
}
}
示例4: ReadLine
public static async Task<string> ReadLine(this IInputStream inputStream)
{
using (var dataReader = new DataReader(inputStream))
{
var line = await dataReader.ReadLine();
dataReader.DetachStream();
return line;
}
}
示例5: ReadTextAsync
internal static async Task<string> ReadTextAsync(this StorageFile file)
{
using (var fs = await file.OpenAsync(FileAccessMode.Read))
{
using (var inStream = fs.GetInputStreamAt(0))
{
using (var dataReader = new DataReader(inStream))
{
await dataReader.LoadAsync((uint)fs.Size);
var data = dataReader.ReadString((uint)fs.Size);
dataReader.DetachStream();
return data;
}
}
}
}
示例6: CopyToNetStreamWithProgress
/// <summary>
/// Копировать из RT потока в .NET поток с прогрессом.
/// </summary>
/// <param name="src">Исхоный поток.</param>
/// <param name="outStream">Поток результата.</param>
/// <param name="progress">Прогресс.</param>
/// <param name="token">Токен отмены.</param>
/// <param name="bufferSize">Размер буфера.</param>
/// <returns>Таск.</returns>
public static async Task CopyToNetStreamWithProgress(this IInputStream src, Stream outStream, IProgress<ulong> progress, CancellationToken token, uint bufferSize = 16384)
{
ulong totalRead = 0;
using (var rd = new DataReader(src))
{
progress.Report(0);
do {
token.ThrowIfCancellationRequested();
var r = await rd.LoadAsync(bufferSize);
totalRead += r;
progress.Report(totalRead);
if (r <= 0) break;
var buf = new byte[r];
rd.ReadBytes(buf);
await outStream.WriteAsync(buf, 0, (int)r, token);
} while (true);
rd.DetachStream();
}
}
示例7: ReadFromFile
public static async Task<string> ReadFromFile(
string fileName,
StorageFolder folder = null)
{
folder = folder ?? ApplicationData.Current.LocalFolder;
var file = await folder.GetFileAsync(fileName);
using (var fs = await file.OpenAsync(FileAccessMode.Read))
{
using (var inStream = fs.GetInputStreamAt(0))
{
using (var reader = new DataReader(inStream))
{
await reader.LoadAsync((uint)fs.Size);
string data = reader.ReadString((uint)fs.Size);
reader.DetachStream();
return data;
}
}
}
}
示例8: RetrieveLinkerTimestamp
public static async Task<DateTimeOffset?> RetrieveLinkerTimestamp(Assembly assembly)
{
var pkg = Windows.ApplicationModel.Package.Current;
if (null == pkg)
{
return null;
}
var assemblyFile = await pkg.InstalledLocation.GetFileAsync(assembly.ManifestModule.Name);
if (null == assemblyFile)
{
return null;
}
using (var stream = await assemblyFile.OpenSequentialReadAsync())
{
using (var reader = new DataReader(stream))
{
const int PeHeaderOffset = 60;
const int LinkerTimestampOffset = 8;
//read first 2048 bytes from the assembly file.
byte[] b = new byte[2048];
await reader.LoadAsync((uint)b.Length);
reader.ReadBytes(b);
reader.DetachStream();
//get the pe header offset
int i = System.BitConverter.ToInt32(b, PeHeaderOffset);
//read the linker timestamp from the PE header
int secondsSince1970 = System.BitConverter.ToInt32(b, i + LinkerTimestampOffset);
var dt = new DateTimeOffset(1970, 1, 1, 0, 0, 0, DateTimeOffset.Now.Offset) + DateTimeOffset.Now.Offset;
return dt.AddSeconds(secondsSince1970);
}
}
}
示例9: ValidateAndLoadSketch
private async void ValidateAndLoadSketch()
{
if (!_isJavascriptReady || !_isBrowserLoaded)
return;
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///sketch.pde", UriKind.RelativeOrAbsolute));
using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (var inStream = fs.GetInputStreamAt(0))
{
using (var dataReader = new DataReader(inStream))
{
await dataReader.LoadAsync((uint)fs.Size);
_sketchText = dataReader.ReadString((uint)fs.Size);
dataReader.DetachStream();
}
}
}
if (_sketchText != "")
Browser.InvokeScript("loadSketch", new[] { _sketchText });
}
示例10: LoadCookiesAsync
public async Task LoadCookiesAsync(Guid requestId)
{
string data = null;
var cookieContainer = new CookieContainer();
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(CookieCacheFile, CreationCollisionOption.OpenIfExists);
using (var fs = await file.OpenAsync(FileAccessMode.Read))
{
using (var inStream = fs.GetInputStreamAt(0))
{
using (var dataReader = new DataReader(inStream))
{
await dataReader.LoadAsync((uint)fs.Size);
data = dataReader.ReadString((uint)fs.Size);
dataReader.DetachStream();
var cookies = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, Cookie>>>(data);
if (cookies != null)
{
foreach (var cookieSet in cookies)
{
foreach (var cookie in cookieSet.Value)
{
cookieContainer.Add(new Uri(cookie.Key), cookie.Value);
}
}
}
this.knownCookies = cookieContainer;
this.persistentCookies = cookies ?? new Dictionary<string, Dictionary<string, Cookie>>();
}
}
}
Trace.Verbose(requestId, "Loaded {0} cookies: {1}\r\n", cookieContainer.Count, data);
}
示例11: Recive
public static async Task<string> Recive(StreamSocket streamSocket, List<string> orstarts, List<string> orends, List<string> andstarts, List<string> andends)
{
string returnString = string.Empty;
try
{
using (var dataReader = new DataReader(streamSocket.InputStream))
{
dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
dataReader.InputStreamOptions = InputStreamOptions.Partial;
var end = false;
while (!end && await dataReader.LoadAsync(64000) != 0)
{
string readString;
var buffer = dataReader.ReadBuffer(dataReader.UnconsumedBufferLength);
using (var dr = DataReader.FromBuffer(buffer))
{
var bytes1251 = new Byte[buffer.Length];
dr.ReadBytes(bytes1251);
readString = Encoding.GetEncoding("UTF-8").GetString(bytes1251, 0, bytes1251.Length);
}
if (!string.IsNullOrEmpty(readString))
returnString += readString;
if (readString == null)
{
end = true;
}
else if (orstarts.FirstOrDefault(o => returnString.StartsWith(o)) != null)
{
end = true;
}
else if (orends.FirstOrDefault(o => returnString.EndsWith(o)) != null)
{
end = true;
}
else if (andstarts.FirstOrDefault(o => returnString.StartsWith(o)) != null
&& andends.FirstOrDefault(o => returnString.EndsWith(o)) != null)
{
end = true;
}
}
dataReader.DetachStream();
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
returnString = string.Empty;
}
return returnString;
}
示例12: 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(); }
}
示例13: Connect
public IAsyncOperation<string> Connect() {
var window = CoreWindow.GetForCurrentThread();
return Task.Run<string>(async () =>
{
try
{
var socket = this.socket = new Windows.Networking.Sockets.StreamSocket();
await socket.ConnectAsync(new HostName("talk.google.com"), "5222", SocketProtectionLevel.PlainSocket);
await log(window, "connected!");
reader = new DataReader(socket.InputStream);
writer = new DataWriter(socket.OutputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
Write("<?xml version='1.0'?>\n<stream:stream to='" + server + "' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");
xmlStream = new XmlStream();
bool shouldRead = true;
xmlStream.SetCallback(async (promptRead, data) => {
await log(window, "data " + data);
if (promptRead)
{
if (shouldRead)
{
await log(window, "prompt read");
await reader.LoadAsync(4096);
var buffer = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(buffer);
await log(window, "in " + Encoding.UTF8.GetString(buffer, 0, buffer.Length));
xmlStream.Update(buffer, 0, buffer.Length);
}
else
{
await log(window, "read blocked");
}
}
else if (data.IndexOf("stream:features") != -1)
{
Write("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls' />");
}
else if (data.IndexOf("proceed") != -1)
{
await log(window, "SSL Strength: " + socket.Information.ProtectionLevel);
writer.DetachStream();
reader.DetachStream();
shouldRead = false;
if (server == "gmail.com")
{
await socket.UpgradeToSslAsync(SocketProtectionLevel.Ssl, new Windows.Networking.HostName("gmail.com"));
}
else
{
await socket.UpgradeToSslAsync(SocketProtectionLevel.Ssl, new Windows.Networking.HostName("talk.google.com"));
}
writer = new DataWriter(socket.OutputStream);
reader = new DataReader(socket.InputStream);
reader.InputStreamOptions = InputStreamOptions.Partial;
await log(window, "upgraded!");
await log(window, "SSL Strength: " + socket.Information.ProtectionLevel);
Write("<?xml version='1.0'?>\n<stream:stream to='" + server + "' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");
xmlStream.SetCallback(async (shouldRead2, data2) =>
{
await log(window, "data " + data2);
if (shouldRead2)
{
await reader.LoadAsync(4096);
var buffer = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(buffer);
await log(window, "in " + Encoding.UTF8.GetString(buffer, 0, buffer.Length));
xmlStream.Update(buffer, 0, buffer.Length);
}
else if (data2.Contains("X-GOOGLE-TOKEN"))
{
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes('\x00' + this.username + '\x00' + this.auth));
Write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-GOOGLE-TOKEN'>" + token + "</auth>");
}
else if (data2.Contains("failure"))
{
if (Disconnect != null) Disconnect(this, "auth failure");
}
else if (data2.Contains("success"))
{
var messageEvent = Message;
//.........这里部分代码省略.........
示例14: ReadFrom
public async static Task<Tuple<string, bool>> ReadFrom(string fpathname)
{
#if WINDOWS_PHONE
return await Task.Run(() =>
{
using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!storage.FileExists(fpathname))
return new Tuple<string, bool>("", false);
using (var fileStream = storage.OpenFile(fpathname, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fileStream))
{
string data = sr.ReadToEnd();
return new Tuple<string, bool>(data, true);
}
}
}
});
#elif NETFX_CORE
Tuple<string, bool> result = new Tuple<string, bool>("", false);
StorageFile file = null;
try
{
file = await ApplicationData.Current.LocalFolder.GetFileAsync(fpathname);
if (file == null)
return result;
}
catch (Exception)
{
return result;
}
using (var fs = await file.OpenAsync(FileAccessMode.Read))
{
using (var inStream = fs.GetInputStreamAt(0))
{
using (var reader = new DataReader(inStream))
{
await reader.LoadAsync((uint)fs.Size);
string data = reader.ReadString((uint)fs.Size);
reader.DetachStream();
result = new Tuple<string, bool>(data, true);
}
}
}
return result;
#else
return await Task.Run (() => {
try
{
string str = File.ReadAllText(fpathname);
return new Tuple<string, bool>(str, true);
}
catch (Exception)
{
return new Tuple<string, bool>("", false);
}
});
#endif
}
示例15: OnConnectionReceived
/// <summary>
/// Invoked when the socket listener accepts an incoming Bluetooth connection.
/// </summary>
/// <param name="sender">The socket listener that accepted the connection.</param>
/// <param name="args">The connection accept parameters, which contain the connected socket.</param>
private async void OnConnectionReceived(
StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
// Don't need the listener anymore
socketListener.Dispose();
socketListener = null;
try
{
socket = args.Socket;
}
catch (Exception e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage);
});
Disconnect();
return;
}
// Note - this is the supported way to get a Bluetooth device from a given socket
var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName);
writer = new DataWriter(socket.OutputStream);
var reader = new DataReader(socket.InputStream);
bool remoteDisconnection = false;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Connected to Client: " + remoteDevice.Name, NotifyType.StatusMessage);
});
// Infinite read buffer loop
while (true)
{
try
{
// Based on the protocol we've defined, the first uint is the size of the message
uint readLength = await reader.LoadAsync(sizeof(uint));
// Check if the size of the data is expected (otherwise the remote has already terminated the connection)
if (readLength < sizeof(uint))
{
remoteDisconnection = true;
break;
}
uint currentLength = reader.ReadUInt32();
// Load the rest of the message since you already know the length of the data expected.
readLength = await reader.LoadAsync(currentLength);
// Check if the size of the data is expected (otherwise the remote has already terminated the connection)
if (readLength < currentLength)
{
remoteDisconnection = true;
break;
}
string message = reader.ReadString(currentLength);
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ConversationListBox.Items.Add("Received: " + message);
});
}
// Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED).
catch (Exception ex) when ((uint)ex.HResult == 0x800703E3)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Client Disconnected Successfully", NotifyType.StatusMessage);
});
break;
}
}
reader.DetachStream();
if (remoteDisconnection)
{
Disconnect();
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Client disconnected",NotifyType.StatusMessage);
});
}
}