本文整理汇总了C#中IOutputStream.AsStreamForWrite方法的典型用法代码示例。如果您正苦于以下问题:C# IOutputStream.AsStreamForWrite方法的具体用法?C# IOutputStream.AsStreamForWrite怎么用?C# IOutputStream.AsStreamForWrite使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IOutputStream
的用法示例。
在下文中一共展示了IOutputStream.AsStreamForWrite方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WriteResponseAsync
private async Task WriteResponseAsync(string[] requestTokens, IOutputStream outstream)
{
// NOTE: If you change the respBody format, change the Content-Type (below) accordingly
//string respBody = weatherData.HTML;
//string respBody = weatherData.XML;
string respBody = weatherData.JSON;
string htmlCode = "200 OK";
using (Stream resp = outstream.AsStreamForWrite())
{
byte[] bodyArray = Encoding.UTF8.GetBytes(respBody);
MemoryStream stream = new MemoryStream(bodyArray);
// NOTE: If you change the respBody format (above), change the Content-Type accordingly
string header = string.Format("HTTP/1.1 {0}\r\n" +
//"Content-Type: text/html\r\n" + // HTML only
//"Content-Type: text/xml\r\n" + // XML only
"Content-Type: text/json\r\n" + // JSON only
"Content-Length: {1}\r\n" +
"Connection: close\r\n\r\n",
htmlCode, stream.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
await resp.FlushAsync();
}
}
示例2: WriteResponseAsync
private async Task WriteResponseAsync(IRestResponse response, IOutputStream os)
{
using (Stream resp = os.AsStreamForWrite())
{
// Look in the Data subdirectory of the app package
byte[] bodyArray = Encoding.UTF8.GetBytes(response.Data);
MemoryStream stream = new MemoryStream(bodyArray);
string header = string.Format("HTTP/1.1 {0} {1}\r\n" +
"Content-Length: {2}\r\n" +
"Content-Type: application/json\r\n" +
"Connection: close\r\n\r\n",
response.StatusCode,
HttpHelpers.GetHttpStatusCodeText(response.StatusCode),
stream.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
await resp.FlushAsync();
}
}
示例3: WriteResponseAsync
private async Task WriteResponseAsync(string request, IOutputStream os)
{
// Show the html
using (Stream resp = os.AsStreamForWrite())
{
using (var file = File.OpenRead(htmlPath))
{
string header = $"HTTP/1.1 200 OK\r\nContent-Length: {file.Length}\r\n" +
"Content-Type:text/html\r\nConnection: close\r\n\r\n";
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await file.CopyToAsync(resp);
}
}
}
示例4: WriteResponseAsync
private async Task WriteResponseAsync(string request, IOutputStream os)
{
using (Stream resp = os.AsStreamForWrite())
{
using (FileStream sourceStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
{
string mime;
string header = string.Format("HTTP/1.1 200 OK\r\n" +
"Date: " + DateTime.Now.ToString("R") + "\r\n" +
"Server: MeoGoEmbedded/1.0\r\n" +
//"Transfer-Encoding: chunked\r\n" +
"Last-Modified: {2}\r\n" +
"Content-Length: {0}\r\n" +
"Content-Type: {1}\r\n" +
"Connection: close\r\n\r\n",
sourceStream.Length,
_mimeTypeMappings.TryGetValue(Path.GetExtension(FilePath), out mime) ? mime : "application/octet-stream", File.GetLastWriteTime(FilePath).ToString("r"));
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
var b = new byte[1 << 15]; // 32k
int count = 0;
while ((count = sourceStream.Read(b, 0, b.Length)) > 0)
{
await resp.WriteAsync(b, 0, count);
}
await resp.FlushAsync();
};
}
}
示例5: redirectToPage
/// <summary>
/// Redirect to a page
/// </summary>
/// <param name="path">Relative path to page</param>
/// <param name="os"></param>
/// <returns></returns>
private async Task redirectToPage(string path, IOutputStream os)
{
using (Stream resp = os.AsStreamForWrite())
{
byte[] headerArray = Encoding.UTF8.GetBytes(
"HTTP/1.1 302 Found\r\n" +
"Content-Length:0\r\n" +
"Location: /" + path + "\r\n" +
"Connection: close\r\n\r\n");
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await resp.FlushAsync();
}
}
示例6: WriteResponseAsync
private async Task WriteResponseAsync(string[] requestTokens, IOutputStream outstream)
{
// Content body
//string respBody = string.Format(@"<html>
// <head>
// <title>SHT15 Sensor Values</title>
// <meta http-equiv='refresh' content='2' />
// </head>
// <body>
// <p><font size='6'><b>Windows 10 IoT Core and SHT15 Sensor</b></font></p>
// <hr/>
// <br/>
// <table>
// <tr>
// <td><font size='3'>Time</font></td>
// <td><font size='3'>{0}</font></td>
// </tr>
// <tr>
// <td><font size='5'>Temperature</font></td>
// <td><font size='6'><b>{1}°C</b></font></td>
// </tr>
// <tr>
// <td><font size='5'>Temperature</font></td>
// <td><font size='6'><b>{2}F</b></font></td>
// </tr>
// <tr>
// <td><font size='5'>Humidity</font></td>
// <td><font size='6'><b>{3}%</b></font></td>
// </tr>
// <tr>
// <td><font size='5'>Dew Point</font></td>
// <td><font size='6'><b>{4}°C</b></font></td>
// </tr>
// </table>
// </body>
// </html>",
// DateTime.Now.ToString("h:mm:ss tt"),
// String.Format("{0:0.00}", MainPage.TemperatureC),
// String.Format("{0:0.00}", MainPage.TemperatureF),
// String.Format("{0:0.00}", MainPage.Humidity),
// String.Format("{0:0.00}", MainPage.CalculatedDewPoint));
string respBody = MainPage.TemperatureC + ";" + MainPage.TemperatureF + ";" + MainPage.Humidity;
string htmlCode = "200 OK";
using (Stream resp = outstream.AsStreamForWrite())
{
byte[] bodyArray = Encoding.UTF8.GetBytes(respBody);
MemoryStream stream = new MemoryStream(bodyArray);
// Response heeader
string header = string.Format("HTTP/1.1 {0}\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: {1}\r\n" +
"Connection: close\r\n\r\n",
htmlCode, stream.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
await resp.FlushAsync();
}
}
示例7: WriteResponseAsync
private async Task WriteResponseAsync(string[] requestTokens, IOutputStream outstream)
{
string respBody = string.Empty;
try
{
string urlPath = requestTokens.Length > 1 ? requestTokens[1] : string.Empty;
if (urlPath.Equals("/LastHour", StringComparison.OrdinalIgnoreCase))
{
respBody = temperatureData.JsonLastHour;
}
else if (urlPath.Equals("/LastDay", StringComparison.OrdinalIgnoreCase))
{
respBody = temperatureData.JsonLast24Hours;
}
else if (urlPath.Equals("/LastMonth", StringComparison.OrdinalIgnoreCase))
{
respBody = temperatureData.JsonLastMonth;
}
else
{
respBody = temperatureData.JsonCurrent;
}
}
catch (Exception ex)
{
await LogExceptionAsync(nameof(WriteResponseAsync) + "(part 1: getting content)", ex);
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
try
{
string htmlCode = "200 OK";
using (Stream resp = outstream.AsStreamForWrite())
{
byte[] bodyArray = Encoding.UTF8.GetBytes(respBody);
MemoryStream stream = new MemoryStream(bodyArray);
// NOTE: If you change the respBody format (above), change the Content-Type accordingly
string header = $"HTTP/1.1 {htmlCode}\r\n" +
"Content-Type: text/json\r\n" +
$"Content-Length: {stream.Length}\r\n" +
"Connection: close\r\n\r\n";
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
await resp.FlushAsync();
}
}
catch (Exception ex)
{
await LogExceptionAsync(nameof(WriteResponseAsync) + "(part) 2: sending results)", ex);
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
}
示例8: WriteFileToStream
/// <summary>
/// Writes a file to the stream
/// </summary>
/// <param name="file"></param>
/// <param name="os"></param>
/// <returns></returns>
public static async Task WriteFileToStream(StorageFile file, IOutputStream os)
{
using (Stream resp = os.AsStreamForWrite())
{
bool exists = true;
try
{
using (Stream fs = await file.OpenStreamForReadAsync())
{
string header = String.Format("HTTP/1.1 200 OK\r\n" +
"Content-Length: {0}\r\n" +
"Connection: close\r\n\r\n",
fs.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await fs.CopyToAsync(resp);
}
}
catch (FileNotFoundException ex)
{
exists = false;
// Log telemetry event about this exception
var events = new Dictionary<string, string> { { "WebHelper", ex.Message } };
App.Controller.TelemetryClient.TrackEvent("FailedToWriteFileToStream", events);
}
if (!exists)
{
byte[] headerArray = Encoding.UTF8.GetBytes(
"HTTP/1.1 404 Not Found\r\n" +
"Content-Length:0\r\n" +
"Connection: close\r\n\r\n");
await resp.WriteAsync(headerArray, 0, headerArray.Length);
}
await resp.FlushAsync();
}
}
示例9: WriteResponseAsync
//Write the response for HTTP GET's and POST's
private async Task WriteResponseAsync(string RequestMsg, string ResponseMsg, bool urlFound, byte[] bodyArray, IOutputStream os)
{
//try //The appService will die after a day or so. Let 's try catch it seperatly so the server will still return
//{
// var updateMessage = new ValueSet();
// updateMessage.Add("Request", RequestMsg);
// updateMessage.Add("Response", ResponseMsg);
// var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage);
//}
//catch (Exception) { }
try
{
MemoryStream bodyStream = new MemoryStream(bodyArray);
using (Stream response = os.AsStreamForWrite())
{
string header = GetHeader(urlFound, bodyStream.Length.ToString());
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await response.WriteAsync(headerArray, 0, headerArray.Length);
if (urlFound)
await bodyStream.CopyToAsync(response);
await response.FlushAsync();
}
}
catch (Exception ex) {
System.Diagnostics.Debug.WriteLine("Error writing response: " + ex.Message);
}
}
示例10: SocketStream
public SocketStream(IInputStream inputStream, IOutputStream outputStream)
{
this.inputStream = inputStream.AsStreamForRead();
this.outputStream = outputStream.AsStreamForWrite();
}
示例11: WriteResponseAsync
protected override async Task WriteResponseAsync(string request, IOutputStream os)
{
var response = new StatusResponse();
if (request.StartsWith("/api/seed"))
{
var sql = new SqlHelper();
sql.SeedDatabase();
}
if (request.StartsWith("/api/status"))
{
var sql = new SqlHelper();
var info = sql.Get();
response.Status = info.CurrentStatus.ToString();
if (info.CurrentStatus == DishwasherStatus.Clean)
{
response.Details = new StatusResponse.CleanStatusDetails
{
DishwasherRun = sql.GetDishwasherRun()
};
}
else if (info.CurrentStatus == DishwasherStatus.Dirty)
{
response.Details = new StatusResponse.DirtyStatusDetails
{
DirtyTime = info.DirtyDateTime
};
}
else if (info.CurrentStatus == DishwasherStatus.Running)
{
response.Details = new StatusResponse.RunningStatusDetails
{
StartTime = info.CurrentRunStart,
RunCycle = info.CurrentCycle
};
}
}
// Show the html
using (Stream resp = os.AsStreamForWrite())
{
string json;
using (MemoryStream jsonStream = new MemoryStream())
{
var serializer = new DataContractJsonSerializer(typeof(StatusResponse));
serializer.WriteObject(jsonStream, response);
jsonStream.Position = 0;
StreamReader sr = new StreamReader(jsonStream);
json = sr.ReadToEnd();
}
byte[] bodyArray = Encoding.UTF8.GetBytes(json);
using (MemoryStream stream = new MemoryStream(bodyArray))
{
string header = String.Format("HTTP/1.1 200 OK\r\n" +
"Content-Length: {0}\r\n" +
"Content-Type: application/json\r\n" +
"Connection: close\r\n\r\n",
stream.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
}
await resp.FlushAsync();
}
}
示例12: WriteResponseAsync
async Task WriteResponseAsync(string request, IOutputStream os)
{
var RtnString = "Unable to processRequest";
if (!request.StartsWith("error -", StringComparison.CurrentCulture))
{
var apiString = "/api/";
if (request.ToLower().Contains(apiString))
{
request = request.Substring(request.IndexOf(apiString, StringComparison.CurrentCulture) + apiString.Length);
RtnString = ApiProccessor(request);
}
else
{
try
{
var file = await MapPath(request);
RtnString = await ReadFile(file);
}
catch (Exception ex)
{
var header = "<!DOCTYPE html><html><body>";
var footer = "</body></html>";
RtnString = header + "Path: " + request + "<br />" + "Error: " + ex.Message + "<br />" + "Stacktrace: " + ex.StackTrace.Replace("\r\n", "<br/>") + footer;
}
}
}
else
{
RtnString = request;
}
// Show the html
using (Stream resp = os.AsStreamForWrite())
{
// Look in the Data subdirectory of the app package
byte[] bodyArray = Encoding.UTF8.GetBytes(RtnString);
var stream = new MemoryStream(bodyArray);
string header = string.Format("HTTP/1.1 200 OK\r\n" +
"Content-Length: {0}\r\n" +
AllowOriginsHeader +
"Connection: close\r\n\r\n",
stream.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
await resp.FlushAsync();
}
}
示例13: WriteResponseAsync
private async Task WriteResponseAsync(string request, IOutputStream os)
{
// See if the request is for text.html, if yes get the new state
string message = "Unspecified";
string repeat = "0"; // we'll convert this to an int in the client side
bool stateChanged = false;
if (request.Contains("text.html?message="))
{
// sadly we don't have HttpUtility class
// this is so wrong
var stringUrl = "http://localhost" + request; // I have to spoof the url
var parameters = UriExtensions.ParseQueryString(new Uri(stringUrl));
message = parameters["message"];
message = Uri.UnescapeDataString(message);
message = message.Replace("+", " ");
repeat = parameters["repeat"];
stateChanged = true;
}
if (stateChanged)
{
var updateMessage = new ValueSet();
updateMessage.Add("message", message);
updateMessage.Add("repeat", repeat);
var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage);
}
// Show the html
using (Stream resp = os.AsStreamForWrite())
{
// Look in the Data subdirectory of the app package
byte[] bodyArray = Encoding.UTF8.GetBytes(htmlString);
MemoryStream stream = new MemoryStream(bodyArray);
string header = String.Format("HTTP/1.1 200 OK\r\n" +
"Content-Length: {0}\r\n" +
"Connection: close\r\n\r\n",
stream.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
await resp.FlushAsync();
}
}
示例14: WriteResponseAsync
private async Task WriteResponseAsync(IOutputStream os, string method, string data = null)
{
string html = String.Format(RestString, GetContentRequestData == null ? String.Empty : GetContentRequestData(method,data));
using (Stream resp = os.AsStreamForWrite())
{
byte[] bodyArray = Encoding.UTF8.GetBytes(html);
MemoryStream stream = new MemoryStream(bodyArray);
string header = String.Format("HTTP/1.1 200 OK\r\n" + "Content-Length: {0}\r\n" + "Connection: close\r\n\r\n", stream.Length);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
await resp.FlushAsync();
}
}
示例15: WriteResponseAsync
/// <summary>
/// 輸出的資料
/// </summary>
/// <param name="request">http://網址 以後的東西
/// ex. http://1xx.xx.xx.xx/sample.html 則此參數呈現 /sample.html</param>
/// <param name="os"></param>
/// <returns></returns>
private async Task WriteResponseAsync(string request, IOutputStream os)
{
string file = @"Assets\html" + request.Replace("\\", "/");
if (request == "/")
{
file = @"Assets\html\index.html";
}
else if (!System.IO.File.Exists(file))
{
file = @"Assets\html\404.html";
}
using (Stream resp = os.AsStreamForWrite())
{
var contentType = "text/html";
if (System.IO.Path.GetExtension(file).ToLower() == ".jpg" ||
System.IO.Path.GetExtension(file).ToLower() == ".png" ||
System.IO.Path.GetExtension(file).ToLower() == ".jpeg")
{
contentType = "image/jpeg";
}
//很簡單的處理jpg and html 只是測試,別太講究
//Handling MIME and Head roughly.
byte[] bodyArray = File.ReadAllBytes(file);
MemoryStream stream = new MemoryStream(bodyArray);
string header = String.Format("HTTP/1.1 200 OK\r\n" +
"Content-Length: {0}\r\n" +
"content-type: {1}\r\n" +
"Connection: close\r\n\r\n",
stream.Length, contentType);
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await resp.WriteAsync(headerArray, 0, headerArray.Length);
await stream.CopyToAsync(resp);
await resp.FlushAsync();
}
}