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


C# StreamWriter.WriteAsync方法代码示例

本文整理汇总了C#中System.IO.StreamWriter.WriteAsync方法的典型用法代码示例。如果您正苦于以下问题:C# StreamWriter.WriteAsync方法的具体用法?C# StreamWriter.WriteAsync怎么用?C# StreamWriter.WriteAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.StreamWriter的用法示例。


在下文中一共展示了StreamWriter.WriteAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SerializeToStreamAsync

		protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
		{
			using (var writer = new StreamWriter(stream))
			{
                await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
				await writer.FlushAsync();
							
				while (Connected)
				{
					try
					{
						var result = await manualResetEvent.WaitAsync(5000);
						if (Connected == false)
							return;

						if (result == false)
						{
                            await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
							await writer.FlushAsync();

                            if (lastMessageEnqueuedAndNotSent != null)
                            {
								await SendMessage(lastMessageEnqueuedAndNotSent, writer);
                            }
							continue;
						}

						manualResetEvent.Reset();

						object message;
						while (msgs.TryDequeue(out message))
						{
							if (CoolDownWithDataLossInMiliseconds > 0 && Environment.TickCount - lastMessageSentTick < CoolDownWithDataLossInMiliseconds)
                            {
                                lastMessageEnqueuedAndNotSent = message;
                                continue;
                            }

							await SendMessage(message, writer);
						}
					}
					catch (Exception e)
					{
						Connected = false;
						log.DebugException("Error when using events transport", e);
						Disconnected();
						try
						{
							writer.WriteLine(e.ToString());
						}
						catch (Exception)
						{
							// try to send the information to the client, okay if they don't get it
							// because they might have already disconnected
						}

					}
				}
			}
		}
开发者ID:cocytus,项目名称:ravendb,代码行数:60,代码来源:ChangesPushContent.cs

示例2: ExportData

        public static async void ExportData(ADatabase db, List<int> experiments, bool showMessagebox = true)
        {
            try
            {
                List<int> test = ADatabaseWorker.GetAllParametersIDs(db);
                foreach (int experiment in experiments)
                {
                    List<string> writeData = ADatabaseWorker.GetAllDataForExport(db, experiment, test);
                    if (!Directory.Exists("export"))
                        Directory.CreateDirectory("export");
                    using (StreamWriter outfile = new StreamWriter("export\\ExperimentID" + experiment.ToString() + ".csv", false, Encoding.UTF8))
                    {
                        string header = "experimentID; Дата; ";
                        foreach (string parameterName in ADatabase.Parameters)
                        {
                            header += parameterName + "; ";
                        }
                        await outfile.WriteAsync(header + Environment.NewLine);

                        foreach (string line in writeData)
                            await outfile.WriteAsync(line);
                    }
                    if (showMessagebox)
                        MessageBox.Show("Export complete!");
                }
            }
            catch (Exception ex)
            {
            }

        }
开发者ID:EugeneGudima,项目名称:Reflecta,代码行数:31,代码来源:Export.cs

示例3: SendMessage

		private async Task SendMessage(object message, StreamWriter writer)
		{
            var o = JsonExtensions.ToJObject(message);        
            await writer.WriteAsync("data: ");
            await writer.WriteAsync(o.ToString(Formatting.None));
            await writer.WriteAsync("\r\n\r\n");
            await writer.FlushAsync();
		}
开发者ID:cocytus,项目名称:ravendb,代码行数:8,代码来源:HttpTracePushContent.cs

示例4: Invoke

 public async Task Invoke(IDictionary<string, object> environment)
 {
     var response = environment["owin.ResponseBody"] as Stream;
     using (var writer = new StreamWriter(response))
     {
         if (_options.IncludeTimestamp)
         {
             await writer.WriteAsync(DateTime.Now.ToLongTimeString());
         }
         await writer.WriteAsync("Hello, " + _options.Name + "!");
     }
 }
开发者ID:925coder,项目名称:MVC5_Samples,代码行数:12,代码来源:HelloWorldComponent.cs

示例5: SerializeToStreamAsync

		protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
		{
			using (var writer = new StreamWriter(stream))
			{
                await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
				await writer.FlushAsync();
							
				while (Connected)
				{
					try
					{
						var result = await manualResetEvent.WaitAsync(5000);
						if (Connected == false)
							return;

						if (result == false)
						{
                            await writer.WriteAsync("data: { \"Type\": \"Heartbeat\" }\r\n\r\n");
							await writer.FlushAsync();
							continue;
						}
						manualResetEvent.Reset();
						object message;
						while (msgs.TryDequeue(out message))
						{
							var obj = JsonConvert.SerializeObject(message, Formatting.None, new EtagJsonConverter());
							await writer.WriteAsync("data: ");
							await writer.WriteAsync(obj);
							await writer.WriteAsync("\r\n\r\n");
							await writer.FlushAsync();
						}
					}
					catch (Exception e)
					{
						Connected = false;
						log.DebugException("Error when using events transport", e);
						Disconnected();
						try
						{
							writer.WriteLine(e.ToString());
						}
						catch (Exception)
						{
							// try to send the information to the client, okay if they don't get it
							// because they might have already disconnected
						}

					}
				}
			}
		}
开发者ID:ReginaBricker,项目名称:ravendb,代码行数:51,代码来源:ChangesPushContent.cs

示例6: WriteFullyQualifiedName

 static void WriteFullyQualifiedName()
 {
     //var personRepo = Factories.RepositoryFactory.GetRepository<IRepository<Person>>();
     var type = typeof(IRepository<Person>);
     var assemblyQualifiedName = typeof(SQLRepository.SQLRepository<Person>);
     var path = PathHelper.GetProjectDirectory();
     var finalPath = Path.Combine(path, "AssemblyNames.txt");
     using (var writer = new StreamWriter(finalPath,true))
     {
         writer.WriteAsync(type.ToString());
         writer.WriteAsync('\n');
         writer.WriteAsync(assemblyQualifiedName.AssemblyQualifiedName);
     }
 }
开发者ID:juancito0316,项目名称:JuansLibrary,代码行数:14,代码来源:Program.cs

示例7: WriteToStreamAsync

		public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
		{
			var values = value as IEnumerable;
			using (var writer = new StreamWriter(writeStream))
			{
				await writer.WriteAsync("<!DOCTYPE html><html><head></head><body>");
				foreach (object line in values)
				{
					await writer.WriteAsync(line + "<br />");
				}
				await writer.WriteAsync("</body></html>");
			}
			writeStream.Close();
		}
开发者ID:Neonsonne,项目名称:dbSpeed,代码行数:14,代码来源:HtmlMediaTypeFormatter.cs

示例8: doShipping

        private async void doShipping(Order order)
        {
            try
            {
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                char seperator = Path.DirectorySeparatorChar;
                FileStream file = await Task.Run<FileStream>(() => File.Create(path + seperator + "dispatch-" + order.OrderID.ToString() + ".txt"));

                if (file != null)
                {
                    string dispatchNote = "Order Summary: " + 
                                          "\r\nOrder ID: " + order.OrderID +
                                          "\r\nOrder Total: " + String.Format("{0:C}", order.TotalValue);

                    StreamWriter writer = new StreamWriter(file);
                    await writer.WriteAsync(dispatchNote);
                    await Task.Run(() => writer.Close());
                }
                else
                {
                    MessageBox.Show(String.Format("Unable to save to file: {0}", file.Name), "Not saved");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception");
            }
        }
开发者ID:RajaBellebon,项目名称:edX,代码行数:28,代码来源:Shipper.cs

示例9: ReadHtmlWithAsyncAwait

        private static async Task ReadHtmlWithAsyncAwait()
        {
            var httpClient = new HttpClient();
            try
            {
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
                HttpResponseMessage message = await httpClient.GetAsync("http://codevalue.net");
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId);

                Console.WriteLine($"response code is {message.StatusCode}");
                var html = await message.Content.ReadAsStringAsync();
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId);

                using (var file = File.Open(@"c:\codevalue.html",FileMode.OpenOrCreate))
                using (var writer=new StreamWriter(file))
                {
                    await writer.WriteAsync(html);
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);

                }
                Console.WriteLine(html);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
           
        }
开发者ID:CodeValue,项目名称:Advanced-Net-New-Employees-2016,代码行数:28,代码来源:Program.cs

示例10: Save

 public async Task Save()
 {
     var roaming = ApplicationData.Current.RoamingFolder;
     if (Session != null)
     {
         var data = JsonConvert.SerializeObject(Session);
         var file = await roaming.CreateFileAsync("settings.json", CreationCollisionOption.ReplaceExisting);
         using (var stream = await file.OpenStreamForWriteAsync())
         using (var writer = new StreamWriter(stream))
         {
             await writer.WriteAsync(data);
             await writer.FlushAsync();
         }
     }
     else
     {
         try
         {
             var file = await roaming.GetFileAsync("settings.json");
             await file.DeleteAsync();
         }
         catch (Exception ex)
         {
             Debug.WriteLine(ex.ToString());
         }
     }
 }
开发者ID:Connorcpu,项目名称:GW2-Win10,代码行数:27,代码来源:AppState.cs

示例11: Invoke

 public Task Invoke(IDictionary<string, object> environment)
 {
     // Get response stream and write to it
     var response = (Stream)environment["owin.ResponseBody"];
     using (var writer = new StreamWriter(response))
         return writer.WriteAsync("Hello from Owin!");
 }
开发者ID:jiantaow,项目名称:AdvDotNet.Samples,代码行数:7,代码来源:GreetingComponent.cs

示例12: InsertOrUpdate

        public async Task<bool> InsertOrUpdate(KeyVaultConfiguration keyVaultConfiguration)
        {
            var writeToFile = JsonConvert.SerializeObject(keyVaultConfiguration);
            var filePath = Path.Combine(
                ConfigurationPath,
                keyVaultConfiguration.VaultName,
                string.Format(ConfigurationFileFormat, keyVaultConfiguration.VaultName));
            
            var directoryPath = Path.Combine(ConfigurationPath, keyVaultConfiguration.VaultName);
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }

            using (var file = File.Create(filePath))
            {
                using (var streamWriter = new StreamWriter(file))
                {
                    await streamWriter.WriteAsync(writeToFile);
                    await streamWriter.FlushAsync();
                    this.allConfigurations.Remove(keyVaultConfiguration);
                    this.allConfigurations.Add(keyVaultConfiguration);
                    return true;
                }
            }
        }
开发者ID:xieyuxi,项目名称:AzureKeyVaultExplorer,代码行数:26,代码来源:KeyVaultConfigurationRepository.cs

示例13: ServeDirectoryListingAsync

		private static async Task ServeDirectoryListingAsync(DirectoryInfo root, DirectoryInfo directory, HttpListenerResponse response)
		{
			StringBuilder listBuilder = new StringBuilder();

			foreach (FileInfo file in directory.EnumerateFiles())
			{
				String target = directory.IsSameDirectory(root) ? file.Name
				                                                : Path.Combine(directory.Name, file.Name);
				listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, file.Name);
			}

			foreach (DirectoryInfo subDirectory in directory.EnumerateDirectories())
			{
				String target = directory.IsSameDirectory(root) ? subDirectory.Name
				                                                : Path.Combine(directory.Name, subDirectory.Name);
				listBuilder.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", target, subDirectory.Name);
			}

			String htmlResponse = String.Format("<ul>{0}</ul>", listBuilder.ToString());

			response.ContentType = "text/html";
			response.ContentLength64 = htmlResponse.Length;
			response.AddHeader("Date", DateTime.Now.ToString("r"));

			response.StatusCode = (Int32)HttpStatusCode.OK; // Must be set before writing to OutputStream.

			using (StreamWriter writer = new StreamWriter(response.OutputStream))
			{
				await writer.WriteAsync(htmlResponse).ConfigureAwait(false);
			}
		}
开发者ID:piedar,项目名称:Hushpuppy,代码行数:31,代码来源:DirectoryListingService.cs

示例14: SearchAsync

        public async Task<VenueSearchResponse> SearchAsync(VenueSearchRequest searchRequest)
        {
            if (searchRequest == null)
            {
                throw new NoNullAllowedException("A valid search request is required.");
            }
            var request = WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/json";

            var data = JsonConvert.SerializeObject(searchRequest);
            using (var stream = await request.GetRequestStreamAsync())
            {
                using (var writer = new StreamWriter(stream))
                {
                    await writer.WriteAsync(data);
                }
            }

            request.ContentLength = data.Length;
            var response = await request.GetResponseAsync();
            using (var stream = response.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    return JsonConvert.DeserializeObject<VenueSearchResponse>(reader.ReadToEnd());
                }
            }
        }
开发者ID:dlswimmer,项目名称:locu.net,代码行数:29,代码来源:LocuClient.cs

示例15: RedeemRefreshTokenInternalAsync

        private static async Task<TokenResponse> RedeemRefreshTokenInternalAsync(OAuthAccount account)
        {
            HttpWebRequest request = WebRequest.CreateHttp(account.TokenService);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            var requestStream = await request.GetRequestStreamAsync();
            var writer = new StreamWriter(requestStream);

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("client_id={0}", Uri.EscapeDataString(account.ClientId));
            sb.AppendFormat("&redirect_uri={0}", Uri.EscapeDataString(account.RedirectUri));
            sb.AppendFormat("&client_secret={0}", Uri.EscapeDataString(account.ClientSecret));
            sb.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(account.RefreshToken));
            sb.Append("&grant_type=refresh_token");
            if (null != account.Resource)
                sb.AppendFormat("&resource={0}", Uri.EscapeDataString(account.Resource));

            var content = sb.ToString();
            await writer.WriteAsync(content);
            await writer.FlushAsync();

            var response = await request.GetResponseAsync() as HttpWebResponse;
            if (null != response && response.StatusCode == HttpStatusCode.OK)
            {
                var responseStream = response.GetResponseStream();
                if (null != responseStream)
                {
                    var reader = new StreamReader(responseStream);
                    return JsonConvert.DeserializeObject<TokenResponse>(await reader.ReadToEndAsync());
                }
            }
            return null;
        }
开发者ID:ahaadi,项目名称:markdown-scanner,代码行数:34,代码来源:OAuthTokenGenerator.cs


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