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


C# IOutputStream.AsStreamForWrite方法代码示例

本文整理汇总了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();
            }
        }
开发者ID:JimGaleForce,项目名称:iot-build-lab,代码行数:29,代码来源:HttpServer.cs

示例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();
     }
 }
开发者ID:kkronyak,项目名称:restup,代码行数:20,代码来源:HttpServer.cs

示例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);
         }
     }
 }
开发者ID:jmservera,项目名称:ConnectedChristmasTree,代码行数:15,代码来源:CustomWebServer.cs

示例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();
                };
            }
        }
开发者ID:nudaca,项目名称:simplehttpserver.uwp,代码行数:31,代码来源:HttpServer.cs

示例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();
     }
 }
开发者ID:VictorBarbosa,项目名称:securitysystem,代码行数:19,代码来源:WebServer.cs

示例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}&deg;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}&deg;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();
            }
        }
开发者ID:Nick287,项目名称:IoTDeviceService,代码行数:65,代码来源:HttpServer.cs

示例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();
                }
            }
        }
开发者ID:torgeirhansen,项目名称:SimpleWeatherStation,代码行数:64,代码来源:HttpServer.cs

示例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();
            }
        }
开发者ID:jadeiceman,项目名称:securitysystem-1,代码行数:45,代码来源:WebHelper.cs

示例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);
            }
        }
开发者ID:admin4cc,项目名称:sprinklerServer,代码行数:29,代码来源:HttpRestServer.cs

示例10: SocketStream

 public SocketStream(IInputStream inputStream, IOutputStream outputStream)
 {
     this.inputStream = inputStream.AsStreamForRead();
     this.outputStream = outputStream.AsStreamForWrite();
 }
开发者ID:dsmithson,项目名称:KnightwareCore,代码行数:5,代码来源:SocketStream.cs

示例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();
            }
        }
开发者ID:ChrisMancini,项目名称:DishwasherMonitor,代码行数:71,代码来源:RestAPI.cs

示例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();
            }

        }
开发者ID:nSwann09,项目名称:Pi-WebLEDController,代码行数:51,代码来源:HttpServer.cs

示例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();
            }

        }
开发者ID:timothystewart6,项目名称:WebServerIoT,代码行数:47,代码来源:BackgroundTask.cs

示例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();
     }
 }
开发者ID:LeighCurran,项目名称:IoTExamples,代码行数:14,代码来源:RestServer.cs

示例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();
            }
            
        }
开发者ID:donma,项目名称:Windows10IoT-TinyHttpServer,代码行数:46,代码来源:TinyHttpdServer.cs


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