Created
February 12, 2022 11:57
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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