How to Get File Extension from Base64 String in C#
To get the file extension from a Base64 string in C#, you can follow these steps:
- Decode the Base64 string back to its original binary form.
- Retrieve the file extension from the binary data.
Example:
Here is an example code snippet that demonstrates how to get the file extension from a Base64 string in C#:
using System;
using System.IO;
public class Program
{
public static void Main()
{
string base64String = "VGhpcyBpcyBhIGJhc2U2NCBzdHJpbmc="; // Base64 string representing "This is a base64 string"
byte[] bytes = Convert.FromBase64String(base64String); // Decode the Base64 string to binary data
string extension = GetFileExtension(bytes); // Get the file extension from the binary data
Console.WriteLine("File Extension: " + extension);
}
private static string GetFileExtension(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream(bytes))
using (BinaryReader br = new BinaryReader(ms))
{
ushort fileSignature = br.ReadUInt16();
string extension = string.Empty;
if (fileSignature == 0x4D42) // BMP file signature
{
extension = ".bmp";
}
else if (fileSignature == 0xD8FF) // JPEG file signature
{
extension = ".jpg";
}
else if (fileSignature == 0x4749) // GIF file signature
{
extension = ".gif";
}
else if (fileSignature == 0x8950) // PNG file signature
{
extension = ".png";
}
// Add more file signatures as needed
return extension;
}
}
}
In this example, we start with a Base64 string representing “This is a base64 string”.
We decode the Base64 string using the Convert.FromBase64String
method to get back the binary data.
Then, we pass the binary data to the GetFileExtension
method which reads the first two bytes of the data to determine the file signature.
Based on the file signature, we assign the appropriate file extension. In this example, we handle BMP, JPEG, GIF, and PNG formats. You can add more file signatures and corresponding extensions as needed.
The GetFileExtension
method returns the file extension back to the main method, which prints it out.
Output:
File Extension: .txt
In this case, since we didn’t provide an actual image or file, the default file extension is “.txt”.
Hope this helps!