Skip to content

Instantly share code, notes, and snippets.

@ArisAgnew
Created February 12, 2022 11:57
Show Gist options
  • Select an option

  • Save ArisAgnew/fdf9c12b128202a94c5f166cefffaafd to your computer and use it in GitHub Desktop.

Select an option

Save ArisAgnew/fdf9c12b128202a94c5f166cefffaafd to your computer and use it in GitHub Desktop.
The code snippet is a gauge of writing a piece of information to a file in an asynchronous way
Task.Run(ProcessWriteAsync); // main function call
async Task ProcessWriteAsync()
{
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string subPath = @"logs\";
string fileName = $@"chatlogs.txt";
DirectoryInfo directoryInfo = new(baseDirectory);
if (directoryInfo is not null)
{
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
directoryInfo.CreateSubdirectory(subPath);
}
await WriteTextAsync(string.Concat(baseDirectory, subPath, fileName), logMsg);
}
async Task WriteTextAsync(string filePath, string text)
{
byte[] encodedText = Encoding.Unicode.GetBytes(text);
using var sourceStream =
new FileStream(
filePath,
FileMode.Append, FileAccess.Write, FileShare.None,
bufferSize: 4096, useAsync: true);
await sourceStream.WriteAsync(encodedText.AsMemory(0, encodedText.Length));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment