C#C
C#3y ago
c0nstant

✅ [SOLVED] Need help with converting async method to a 'normal' method

I tried a few solutions to be able to call an async method from my Main method but those have failed, here is the link:
https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c

Here is my code:
public static class FileEncryptor
        {
            private const int AesKeySize = 256;
            private const int AesBlockSize = 128;
            public const int KeySizeInBytes = AesKeySize / 8;

            /// <summary>
            /// Encrypts a file using a 32 character key.
            /// </summary>
            public static Task EncryptAsync(string inputFilePath, string outputFilePath, string key, CancellationToken token = default)
            {
                if (string.IsNullOrWhiteSpace(key))
                {
                    //if key is empty do jack
                }

                byte[] keyBytes = Encoding.UTF8.GetBytes(key);
                return EncryptAsync(inputFilePath, outputFilePath, keyBytes, token);
            }
            public static async Task EncryptAsync(string inputFilePath, string outputFilePath, byte[] keyBytes, CancellationToken token = default)
            {
                if (!File.Exists(inputFilePath))
                {
                }
                if (keyBytes.Length != KeySizeInBytes)
                { 
                }
                using var aes = Aes.Create();
                aes.BlockSize = AesBlockSize;
                aes.KeySize = AesKeySize;
                aes.Key = keyBytes;

                await using FileStream outFileStream = new(outputFilePath, FileMode.Create);

                // Write initialization vector to beginning of file
                await outFileStream.WriteAsync(aes.IV.AsMemory(0, aes.IV.Length), token);

                ICryptoTransform encryptor = aes.CreateEncryptor();
                await using CryptoStream cryptoStream = new(
                    outFileStream,
                    encryptor,
                    CryptoStreamMode.Write);

                await using var inputFileStream = new FileStream(inputFilePath, FileMode.Open);

                await inputFileStream.CopyToAsync(cryptoStream, token);
            }
        }

So how do I go about converting this to something that I can easily call like a normal function from Main?
Was this page helpful?