本文整理汇总了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
}
}
}
}
}
示例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)
{
}
}
示例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();
}
示例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 + "!");
}
}
示例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
}
}
}
}
}
示例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);
}
}
示例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();
}
示例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");
}
}
示例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);
}
}
示例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());
}
}
}
示例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!");
}
示例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;
}
}
}
示例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);
}
}
示例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());
}
}
}
示例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;
}