[Solved] How to check for a valid Base64 encoded string c#


I'm developing an ASP.NET Core application where I need to verify if a string is a valid Base64 encoded string. I aim to circumvent any exceptions that might arise from invalid Base64 strings by simply checking the validity and returning false if it's invalid. This proactive approach not requried the need for exception handling, as I anticipate instances where the provided value may not conform to Base64 encoding standards.

Here's the solution using Convert.TryFromBase64String in C# 7.2:

        public static bool IsBase64Valid(string base64String)
        {
            // We create a span of bytes with the same length as the input string
            Span<byte> buffer = new Span<byte>(new byte[base64String.Length]);
            
            // We attempt to parse the Base64 string into bytes using TryFromBase64String
            // This method returns true if successful and false otherwise
            bool isValid = Convert.TryFromBase64String(base64String, buffer, out int bytesParsed);

            // We return the result indicating whether the string is a valid Base64 encoding
            return isValid;
        }
    


Using Convert.TryFromBase64String from C# 7.2 provides a more efficient and safer way to validate Base64 strings. It avoids the need for exception handling, which can improve performance, especially when dealing with large numbers of strings. TryFromBase64String allows us to check whether a string is a valid Base64 encoding without the overhead of exception handling. Using the Span<byte> type, we can efficiently work with the underlying memory without unnecessary allocations. 

using System;

public class Base64Checker
{
    public bool IsBase64String(string input)
    {
        // Check if the input is null or empty
        if (string.IsNullOrEmpty(input))
        {
            return false;
        }

        // Check if the length of the input string is not divisible by 4, which indicates invalid Base64 encoding
        if (input.Length % 4 != 0)
        {
            return false;
        }

        try
        {
            // Decode the input string to bytes
            byte[] data = Convert.FromBase64String(input);

            // Encode the bytes back to a string and compare with the original input to ensure they match
            string encodedText = Convert.ToBase64String(data);
            return input.Equals(encodedText);
        }
        catch (FormatException)
        {
            // Input is not a valid Base64 string
            return false;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Instantiate the Base64Checker class
        Base64Checker base64Checker = new Base64Checker();

        // Test cases
        string validBase64String = "SGVsbG8gV29ybGQh"; // "Hello World!" in Base64
        string invalidBase64String = "InvalidBase64String";

        // Check if the strings are valid Base64 encoded
        bool isValidBase64 = base64Checker.IsBase64String(validBase64String);
        bool isInvalidBase64 = base64Checker.IsBase64String(invalidBase64String);

        // Print the results
        if (isValidBase64)
        {
            Console.WriteLine("The input string is a valid Base64 encoded string.");
        }
        else
        {
            Console.WriteLine("The input string is not a valid Base64 encoded string.");
        }

        if (isInvalidBase64)
        {
            Console.WriteLine("The input string is a valid Base64 encoded string.");
        }
        else
        {
            Console.WriteLine("The input string is not a valid Base64 encoded string.");
        }
    }
}
  • We create a class called Base64Checker that contains a method IsBase64String which takes a string as input and returns a boolean indicating whether the input is a valid Base64 encoded string and In the IsBase64String method, we perform the following checks:
  • Checking if the input string is null or empty. If it is, we return false.Checking if the length of the input string is divisible by 4, as Base64 encoded strings must have a length that is a multiple of 4. If it's not, we return false.Attempt to decode the input string from Base64 to bytes using Convert.FromBase64String. If the input is not a valid Base64 string, a FormatException will be thrown, and we catch it and return false.