C# में Base64 Decode — Convert.FromBase64String() गाइड

·Game Developer & Unity Engineer·समीक्षकEmma Richardson·प्रकाशित

मुफ़्त Base64 Decode Online को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।

Base64 Decode Online ऑनलाइन आज़माएं →

मैंने जितने भी .NET projects में काम किया है, सभी में कभी न कभी Base64 decode करनी पड़ी है — Kubernetes secrets से connection strings निकालना, webhooks से binary payloads पढ़ना, या debugging session के दौरान JWT tokens inspect करना। C# में Base64 decode करने का primary method Convert.FromBase64String() है, जो एक byte[] लौटाता है जिसे आप फिर readable text पाने के लिए Encoding.UTF8.GetString() में पास करते हैं। बिना code लिखे quick check के लिए, ToolDeck का Base64 decoder browser में तुरंत इसे handle करता है। यह guide Convert.FromBase64String(), .NET 5+ के लिए span-based TryFromBase64String(), high-performance System.Buffers.Text.Base64 API, JWT payload extraction, file और API response decoding, CryptoStream से streaming, और वे चार गलतियाँ cover करती है जो C# developers को सबसे अधिक परेशान करती हैं।

  • Convert.FromBase64String(s) + Encoding.UTF8.GetString(bytes) standard दो-चरण pipeline है — सभी .NET versions में काम करती है।
  • Convert.TryFromBase64String() अमान्य इनपुट पर exceptions से बचता है और Span<byte> में लिखता है — .NET 5+ पर hot paths के लिए आदर्श।
  • System.Buffers.Text.Base64.DecodeFromUtf8() performance-critical services में UTF-8 byte buffers के लिए zero-allocation decoding देता है।
  • JWT tokens Base64url उपयोग करते हैं (+ और / के बजाय - और _) — Convert.FromBase64String() कॉल करने से पहले इनपुट normalize करना आवश्यक है।
  • CryptoStream + FromBase64Transform सब कुछ memory में load किए बिना large files की streaming decoding handle करता है।

Base64 Decoding क्या है?

Base64 encoding binary data को 64-character ASCII alphabet में convert करता है ताकि यह text-only transport — JSON fields, HTTP headers, email bodies, XML attributes — से सुरक्षित रूप से गुजर सके। Input के प्रत्येक 3 bytes 4 Base64 characters बनते हैं, इसलिए Base64 output हमेशा original से लगभग 33% बड़ा होता है। Decoding इस transformation को उलटता है। अंत में = padding decoder को बताती है कि अंतिम group से कितने bytes trim करने हैं। एक = का मतलब है कि अंतिम block में 2 bytes थे; == का मतलब है कि उसमें 1 byte था। Base64 encryption नहीं है — कोई भी इसे reverse कर सकता है। इसका उद्देश्य confidentiality नहीं, बल्कि उन channels से safe transport है जो raw binary को खराब कर देते हैं।

Before · text
After · text
cmVkaXM6Ly9jYWNoZS1wcm9kLmludGVybmFsOjYzNzkvc2Vzc2lvbi1zdG9yZQ==
redis://cache-prod.internal:6379/session-store

Convert.FromBase64String() — Standard Decoding Method

Convert.FromBase64String() method Framework 1.1 के दिनों से .NET में है। कोई NuGet packages नहीं, System से परे कोई extra imports नहीं — बस इसे call करें और byte[] वापस पाएं। C# string में Base64 decode करने की दो-चरण pipeline हमेशा एक जैसी है: bytes पाने के लिए Convert.FromBase64String(), फिर उन bytes को text के रूप में interpret करने के लिए Encoding.UTF8.GetString()। समस्या यह है कि method raw bytes लौटाता है, string नहीं। उन bytes को वापस text में convert करने के लिए आपको सही Encoding चुनना होगा, और यह choice अधिकांश लोगों की अपेक्षा से अधिक मायने रखती है। गलत encoding चुपचाप mojibake — garbled characters — produce करती है, कोई exception आपको warn नहीं करती।

Minimal working example

C# (.NET 6+)
using System;
using System.Text;

// Kubernetes secret में Base64 के रूप में stored connection string
string encoded = "cmVkaXM6Ly9jYWNoZS1wcm9kLmludGVybmFsOjYzNzkvc2Vzc2lvbi1zdG9yZQ==";

byte[] decodedBytes = Convert.FromBase64String(encoded);
string connectionString = Encoding.UTF8.GetString(decodedBytes);

Console.WriteLine(connectionString);
// redis://cache-prod.internal:6379/session-store

जब तक कोई विशेष कारण न हो, हमेशा Encoding.UTF8 उपयोग करें। .NET runtime strings को internally UTF-16 के रूप में represent करता है, लेकिन system boundaries पार करने वाला अधिकांश data (API responses, config files, secrets) UTF-8 encode होता है। multi-byte characters वाले data पर Encoding.ASCII उपयोग करने से वे चुपचाप ? से replace हो जाते हैं — कोई exception नहीं, सिर्फ corrupted output।

Round-trip verification

C# (.NET 6+)
using System;
using System.Text;

string original = "postgres://db-admin:Kx8!mQ@db-prod.us-east-1.internal:5432/orders";

// Encode
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(original));
Console.WriteLine(encoded);
// cG9zdGdyZXM6Ly9kYi1hZG1pbjpLeDghbVFAZGItcHJvZC51cy1lYXN0LTEuaW50ZXJuYWw6NTQzMi9vcmRlcnM=

// Decode
byte[] decoded = Convert.FromBase64String(encoded);
string recovered = Encoding.UTF8.GetString(decoded);

Console.WriteLine(recovered == original); // True

सही Encoding चुनना

GetString() में पास की जाने वाली Encoding वही होनी चाहिए जो data originally encode करते समय उपयोग की गई थी। गलत चुनें और बिना किसी exception के garbage characters मिलते हैं — decoder खुशी से nonsense produce करता रहता है। यहाँ practical breakdown है:

  • Encoding.UTF8 — सुरक्षित default। ASCII और सभी Unicode handle करता है। जब तक कोई और कारण न हो, यही उपयोग करें।
  • Encoding.ASCII — केवल pure 7-bit ASCII data के लिए। Multi-byte characters ? बन जाते हैं।
  • Encoding.Unicode — .NET में यह UTF-16LE है। कुछ Windows-internal strings और PowerShell exports यही उपयोग करते हैं।
  • Encoding.Latin1 — legacy Western European encoding। पुराने SOAP services और mainframe integrations में दिखता है।
C# (.NET 6+)
using System;
using System.Text;

// Same bytes, different encodings — different results
byte[] decoded = Convert.FromBase64String("w7bDvMOk");

Console.WriteLine(Encoding.UTF8.GetString(decoded));    // öüä  (correct)
Console.WriteLine(Encoding.ASCII.GetString(decoded));   // ??????  (lost)
Console.WriteLine(Encoding.Latin1.GetString(decoded));  // öüä  (mojibake)

Error handling के साथ reusable decode helper

चूँकि Convert.FromBase64String() bad input पर throw करता है और whitespace-stripping dance बार-बार करनी पड़ती है, मैं अधिकांश projects में एक छोटा helper रखता हूँ:

C# (.NET 6+)
using System;
using System.Text;

static class Base64Helper
{
    public static string? DecodeToString(string encoded)
    {
        if (string.IsNullOrWhiteSpace(encoded))
            return null;

        // .NET के decoder द्वारा reject किए जाने वाले whitespace हटाएँ
        string cleaned = encoded
            .Replace("
", "")
            .Replace("
", "")
            .Replace(" ", "")
            .Trim();

        try
        {
            byte[] bytes = Convert.FromBase64String(cleaned);
            return Encoding.UTF8.GetString(bytes);
        }
        catch (FormatException)
        {
            return null; // या domain-specific exception throw करें
        }
    }
}

// Usage
string? decoded = Base64Helper.DecodeToString("  cmVkaXM6Ly9jYWNoZQ==  \n");
Console.WriteLine(decoded); // redis://cache
नोट:Convert.FromBase64String() FormatException throw करता है यदि इनपुट में Base64 alphabet के बाहर के characters हों — spaces, newlines, और URL-safe characters जैसे - और _ सहित। ऊपर का helper whitespace को automatically handle करता है।

Non-Standard Types में Base64 Decoding

Decoder हमेशा आपको byte[] देता है। आप उन bytes के साथ क्या करते हैं यह original data पर निर्भर करता है। कभी-कभी यह 16 raw bytes के रूप में stored GUID होता है, कभी-कभी serialized protobuf message, कभी-कभी binary format में timestamp। यहाँ वे conversions हैं जो मैं सबसे अधिक use करता हूँ।

Base64 से GUID

C# (.NET 6+)
using System;

// कुछ APIs GUIDs को 36-char hex strings के बजाय 22-char Base64 के रूप में भेजते हैं
string compactGuid = "C0HqetxMckKlZw4CssPUeQ==";
byte[] guidBytes = Convert.FromBase64String(compactGuid);
Guid recovered = new Guid(guidBytes);

Console.WriteLine(recovered);
// 7aea41c0-4cdc-4272-a567-0e02b2c3d479

Base64 से System.Text.Json के साथ deserialized JSON

C# (.NET 6+)
using System;
using System.Text;
using System.Text.Json;

// Message queue से Base64-encoded JSON payload
string encoded = "eyJzZXJ2aWNlIjoicGF5bWVudC1nYXRld2F5IiwicmVnaW9uIjoiZXUtd2VzdC0xIiwicmVwbGljYXMiOjR9";

byte[] jsonBytes = Convert.FromBase64String(encoded);
string json = Encoding.UTF8.GetString(jsonBytes);
Console.WriteLine(json);
// {"service":"payment-gateway","region":"eu-west-1","replicas":4}

// Record में deserialize करें
var deployEvent = JsonSerializer.Deserialize<DeployEvent>(jsonBytes);
Console.WriteLine($"{deployEvent!.Service} in {deployEvent.Region}");
// payment-gateway in eu-west-1

record DeployEvent(string Service, string Region, int Replicas);

Base64 से hex string

C# (.NET 5+)
using System;

// Base64 के रूप में stored SHA-256 hash
string hashBase64 = "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg=";
byte[] hashBytes = Convert.FromBase64String(hashBase64);
string hex = Convert.ToHexString(hashBytes);

Console.WriteLine(hex);
// 9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08
चेतावनी:BinaryFormatter उपयोग करके untrusted Base64 data को कभी deserialize न करें। इसमें known remote code execution vulnerabilities हैं और यह .NET 8+ में obsolete है। यदि encoded content किसी external source से आती है, तो .NET binary serialization के बजाय इसे JSON या protobuf के रूप में parse करें।

Base64 Decoding Methods Reference

.NET दो namespaces में multiple decoding methods provide करता है। Convert class general-purpose decoding handle करती है, जबकि System.Buffers.Text.Base64 high-throughput scenarios को target करती है जहाँ आप already raw UTF-8 byte buffers के साथ काम कर रहे हों।

मेथड
रिटर्न
इनपुट टाइप
विवरण
Convert.FromBase64String(string)
byte[]
string
एक मानक Base64 string को byte array में डिकोड करता है; अमान्य इनपुट पर FormatException throw करता है
Convert.TryFromBase64String(string, Span<byte>, out int)
bool
string + Span<byte>
कॉलर-allocate Span में डिकोड करने का प्रयास करता है; विफलता पर throw के बजाय false लौटाता है (.NET 5+)
Convert.FromBase64CharArray(char[], int, int)
byte[]
char[] + offset + length
एक char array के सेगमेंट को डिकोड करता है; substrings बनाए बिना buffer parsing के लिए उपयोगी
Convert.TryFromBase64Chars(ReadOnlySpan<char>, Span<byte>, out int)
bool
ReadOnlySpan<char> + Span<byte>
char span से Span-आधारित, zero-allocation डिकोडिंग (.NET 5+)
System.Buffers.Text.Base64.DecodeFromUtf8(ROSpan<byte>, Span<byte>, out int, out int, bool)
OperationStatus
ReadOnlySpan<byte> + Span<byte>
उच्च-प्रदर्शन UTF-8 byte डिकोडिंग; OperationStatus enum लौटाता है (.NET Core 2.1+)
System.Buffers.Text.Base64.DecodeFromUtf8InPlace(Span<byte>, out int)
OperationStatus
Span<byte>
इन-प्लेस डिकोड करता है, इनपुट buffer को overwrite करता है; zero extra allocation (.NET Core 2.1+)

Convert.TryFromBase64String() — Exception-Free Decoding

Try pattern .NET में उन operations के लिए standard है जो user input पर fail हो सकती हैं। .NET 5 से available Convert.TryFromBase64String(), FormatException throw करने के बजाय एक bool लौटाता है। यह decoded bytes को caller-provided Span<byte> में लिखता है, जिसका मतलब है कि आप छोटे payloads के लिए stack-allocated memory उपयोग कर सकते हैं और heap को completely bypass कर सकते हैं।

C# (.NET 5+)
using System;
using System.Text;

string userInput = "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=";

// छोटे payloads के लिए Stack-allocate (< 1KB एक safe rule of thumb है)
Span<byte> buffer = stackalloc byte[256];

if (Convert.TryFromBase64String(userInput, buffer, out int bytesWritten))
{
    string result = Encoding.UTF8.GetString(buffer[..bytesWritten]);
    Console.WriteLine(result);
    // {"host":"10.0.1.50","port":8443}
}
else
{
    Console.WriteLine("Invalid Base64 input — skipping");
}

यह approach request middleware या validation pipelines में बेहतरीन काम करती है जहाँ bad input आना normal है। हर malformed request पर FormatException throw और catch करना scale पर measurable overhead जोड़ता है — TryFromBase64String() इससे completely बचता है।

Decoding के बिना Base64 input validate करना

API controllers में एक common pattern: इनपुट को downstream पास करने से पहले check करें कि यह valid Base64 है या नहीं। आप throwaway buffer allocate करके TryFromBase64String() को validator के रूप में उपयोग कर सकते हैं:

C# (.NET 5+)
using System;

static bool IsValidBase64(string input)
{
    // Maximum decoded size calculate करें
    Span<byte> buffer = stackalloc byte[((input.Length + 3) / 4) * 3];
    return Convert.TryFromBase64String(input, buffer, out _);
}

// API controller में usage
Console.WriteLine(IsValidBase64("eyJob3N0IjoiMTAuMC4xLjUwIn0=")); // True
Console.WriteLine(IsValidBase64("not!!valid!!base64"));              // False
Console.WriteLine(IsValidBase64(""));                                // True (empty is valid)
नोट:Output buffer पर्याप्त बड़ा होना चाहिए। यदि यह बहुत छोटा है, TryFromBase64String() false लौटाता है भले ही input valid हो। सुरक्षित रहने के लिए required size को (inputLength / 4) * 3 के रूप में calculate करें।

File और API Response से Base64 Decode करना

Disk से Base64-encoded file पढ़ना

Certificates, encrypted blobs, और data export files कभी-कभी Base64 text के रूप में आते हैं। आम तरीका: file को string के रूप में पढ़ें, whitespace और line breaks हटाएँ जो FormatException cause करेंगे, bytes में decode करें, और binary output लिखें। Error handling पर ध्यान दें — file I/O errors और Base64 format errors अलग-अलग catch होनी चाहिए।

C# (.NET 6+)
using System;
using System.IO;

string inputPath = "tls-cert.pem.b64";
string outputPath = "tls-cert.pem";

try
{
    string encoded = File.ReadAllText(inputPath).Trim();
    // Line breaks हटाएँ — .NET का decoder उन्हें reject करता है
    encoded = encoded.Replace("
", "").Replace("
", "");

    byte[] decoded = Convert.FromBase64String(encoded);
    File.WriteAllBytes(outputPath, decoded);

    Console.WriteLine($"Decoded {decoded.Length} bytes -> {outputPath}");
}
catch (IOException ex)
{
    Console.Error.WriteLine($"File error: {ex.Message}");
}
catch (FormatException ex)
{
    Console.Error.WriteLine($"Invalid Base64: {ex.Message}");
}

HTTP API response से Base64 field decode करना

Cloud APIs (Azure Key Vault, AWS Secrets Manager, GitHub Contents API) अक्सर binary data को JSON के अंदर embedded Base64 strings के रूप में लौटाते हैं। Workflow हमेशा एक जैसा है: HTTP request करें, JSON response parse करें, Base64 field extract करें, और decode करें। नीचे का example HttpClient और System.Text.Json उपयोग करता है — दोनों .NET 6+ में built-in हैं।

C# (.NET 6+)
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer sk-prod-9f8e7d6c");

try
{
    var response = await client.GetAsync("https://api.example.com/secrets/db-password");
    response.EnsureSuccessStatusCode();

    string body = await response.Content.ReadAsStringAsync();

    // API returns: {"name":"db-password","value":"cG9zdGdyZXM6eGs5bVAycVI=","version":3}
    using var doc = JsonDocument.Parse(body);
    string encodedValue = doc.RootElement.GetProperty("value").GetString()!;

    byte[] decoded = Convert.FromBase64String(encodedValue);
    string secret = Encoding.UTF8.GetString(decoded);

    Console.WriteLine($"Secret: {secret}");
    // Secret: postgres:xk9mP2qR
}
catch (HttpRequestException ex)
{
    Console.Error.WriteLine($"HTTP error: {ex.Message}");
}
catch (FormatException ex)
{
    Console.Error.WriteLine($"Base64 decode failed: {ex.Message}");
}
नोट:Network errors और FormatException के लिए अपने catch blocks अलग रखें। उन्हें एक साथ रखने से यह बताना मुश्किल हो जाता है कि API ने bad data लौटाया या request ही fail हुई। Production में, जब आप FormatException catch करें तो raw Base64 value (या कम से कम उसकी length और पहले 20 characters) log करें — यह debugging को काफी आसान बनाता है।

Command Line से Base64 Decoding

आपको हमेशा compiled project की जरूरत नहीं होती। dotnet-script tool और PowerShell दोनों one-liners से Base64 decoding handle करते हैं। Debugging के दौरान quick inspection के लिए, ये console app बनाने से तेज़ होते हैं।

bash
# PowerShell (Windows में built-in, Linux/macOS पर available)
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("eyJob3N0IjoiMTAuMC4xLjUwIn0="))
# {"host":"10.0.1.50"}

# Linux / macOS native base64 command
echo "eyJob3N0IjoiMTAuMC4xLjUwIn0=" | base64 --decode
# {"host":"10.0.1.50"}

# macOS --decode की जगह -D उपयोग करता है
echo "eyJob3N0IjoiMTAuMC4xLjUwIn0=" | base64 -D

# dotnet-script (install: dotnet tool install -g dotnet-script)
echo 'Console.WriteLine(System.Text.Encoding.UTF8.GetString(Convert.FromBase64String("eyJob3N0IjoiMTAuMC4xLjUwIn0=")));' | dotnet-script eval

# Decode करें और jq से JSON pretty-print करें
echo "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=" | base64 --decode | jq .

Encoded strings को सीधे browser में paste करने के लिए, ToolDeck का Base64 decoder बिना किसी setup के standard और URL-safe दोनों variants handle करता है।

High-Performance Alternative: System.Buffers.Text.Base64

.NET Core 2.1 से available System.Buffers.Text.Base64 class .NET strings के बजाय raw UTF-8 byte spans पर operate करती है। यह string-to-byte conversion overhead को completely bypass करती है — कोई intermediate string allocation नहीं, कोई UTF-16 encoding step नहीं। मैं इसे ASP.NET Core middleware में use करता हूँ जहाँ incoming data already request body से ReadOnlySpan<byte> है। इसे Convert.FromBase64String() में पास करने के लिए string बनाना फालतू में allocations double कर देता है। .NET 8 पर BenchmarkDotNet tests में, span-based path 1 KB से छोटे payloads के लिए लगभग 2-3x तेज़ है और gap बड़े inputs के साथ बढ़ता है क्योंकि GC pressure flat रहती है।

C# (.NET 6+)
using System;
using System.Buffers.Text;
using System.Text;

// HTTP request body से raw UTF-8 bytes simulate करें
byte[] utf8Input = Encoding.UTF8.GetBytes("eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0M30=");

byte[] output = new byte[Base64.GetMaxDecodedFromUtf8Length(utf8Input.Length)];

OperationStatus status = Base64.DecodeFromUtf8(
    utf8Input, output, out int bytesConsumed, out int bytesWritten);

if (status == OperationStatus.Done)
{
    string result = Encoding.UTF8.GetString(output.AsSpan(0, bytesWritten));
    Console.WriteLine(result);
    // {"host":"10.0.1.50","port":8443}
    Console.WriteLine($"Consumed: {bytesConsumed}, Written: {bytesWritten}");
    // Consumed: 44, Written: 31
}
else
{
    Console.WriteLine($"Decode failed: {status}");
    // Possible: InvalidData, DestinationTooSmall, NeedMoreData
}

Return type OperationStatus है — चार values वाला enum: Done, InvalidData, DestinationTooSmall, और NeedMoreData। अंतिम एक streaming data के partial decoding के लिए उपयोगी है। zero allocation के लिए, इसे new byte[] के बजाय ArrayPool<byte>.Shared.Rent() के साथ pair करें।

DecodeFromUtf8InPlace — input buffer overwrite करें

C# (.NET 6+)
using System;
using System.Buffers.Text;
using System.Text;

// Input buffer decoded bytes से overwrite हो जाता है
byte[] data = Encoding.UTF8.GetBytes("c2VydmVyLWNvbmZpZw==");

OperationStatus status = Base64.DecodeFromUtf8InPlace(data, out int bytesWritten);

if (status == OperationStatus.Done)
{
    Console.WriteLine(Encoding.UTF8.GetString(data.AsSpan(0, bytesWritten)));
    // server-config
}
नोट:DecodeFromUtf8InPlace input buffer को modify करता है। इसे तब उपयोग न करें जब आपको बाद में original Base64 string की जरूरत हो — array के पहले bytesWritten bytes में अब decoded data है, और बाकी garbage है।

एक बात ध्यान रखें: System.Buffers.Text.Base64 URL-safe Base64 को directly handle नहीं करता। यदि input - और _ characters उपयोग करता है (JWT tokens, उदाहरण के लिए), तो इन methods को call करने से पहले आपको उन्हें + और / से replace करना होगा। Span-based APIs strictly RFC 4648 standard alphabet के लिए हैं। कोई DecodeFromUtf8Url variant नहीं है — modern APIs में Base64url कितना common है, यह देखते हुए एक surprising gap है।

Terminal Output: Syntax Highlighting के साथ (Spectre.Console)

Spectre.Console library JSON highlighting सहित rich terminal output देती है — CLI tools बनाते समय उपयोगी जो Base64 decode करते हैं और result display करते हैं। इसे dotnet add package Spectre.Console से install करें।

C# (.NET 6+)
using System;
using System.Text;
using Spectre.Console;
using Spectre.Console.Json;

string encoded = "eyJob3N0IjoiMTAuMC4xLjUwIiwicG9ydCI6ODQ0MywibWF4Q29ubiI6MTAwfQ==";
byte[] decoded = Convert.FromBase64String(encoded);
string json = Encoding.UTF8.GetString(decoded);

// Terminal में syntax highlighting के साथ pretty-print करें
AnsiConsole.Write(new JsonText(json));
// Colored JSON output:
// {
//   "host": "10.0.1.50",
//   "port": 8443,
//   "maxConn": 100
// }

यह विशेष रूप से उन CLI tools के लिए उपयोगी है जो remote services से configuration fetch और decode करते हैं। Base64 config decode करें, JSON में deserialize करें, और highlighted output print करें — सब कुछ कुछ lines में। Spectre.Console में table rendering, progress bars, और tree views भी हैं यदि आपको terminal में अधिक complex decoded data structures display करनी हों।

चेतावनी:Spectre.Console output में ANSI escape sequences होते हैं। इसे file में pipe न करें या API से return न करें — इसे केवल terminal display के लिए उपयोग करें।

CryptoStream से Large Base64 Files Streaming करना

File.ReadAllText() से 500 MB Base64 file load करना और फिरConvert.FromBase64String() call करना लगभग 700 MB heap allocate करता है: string itself (UTF-16, इसलिए file size का double) plus decoded byte array।CryptoStream + FromBase64Transform combination chunks में decode करता है, memory usage को constant रखता है।

C# (.NET 6+)
using System.IO;
using System.Security.Cryptography;

string inputPath = "database-export.sql.b64";
string outputPath = "database-export.sql";

using var inputStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
using var transform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces);
using var base64Stream = new CryptoStream(inputStream, transform, CryptoStreamMode.Read);
using var outputStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write);

base64Stream.CopyTo(outputStream);

Console.WriteLine($"Decoded {new FileInfo(outputPath).Length} bytes -> {outputPath}");

FromBase64TransformMode.IgnoreWhiteSpaces flag manual cleanup के बिना line-wrapped Base64 (PEM files, email exports) handle करता है। इस flag के बिना, input में line breaks FormatException cause करते हैं। यह Java केgetMimeDecoder() के .NET के सबसे करीबी equivalent है — यह decoding के दौरान चुपचाप whitespace characters skip करता है।

CryptoStream नाम misleading है — Base64 में कुछ भी cryptographic नहीं है। Microsoft ने FromBase64Transform को System.Security.Cryptography namespace में रखा क्योंकि यह ICryptoTransform implement करता है, वही interface जो AES और अन्य cipher transforms के लिए उपयोग होता है। Stream itself chunks में किसी भी transform से data pipe करता है। इसे एक general-purpose streaming transform pipeline के रूप में सोचें जो गलती से इस namespace में आ गई।

ASP.NET Core scenarios के लिए Async streaming

C# (.NET 6+)
using System.IO;
using System.Security.Cryptography;

async Task DecodeStreamAsync(Stream inputStream, string outputPath)
{
    using var transform = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces);
    using var base64Stream = new CryptoStream(inputStream, transform, CryptoStreamMode.Read);
    await using var outputStream = new FileStream(
        outputPath, FileMode.Create, FileAccess.Write, FileShare.None,
        bufferSize: 81920, useAsync: true);

    await base64Stream.CopyToAsync(outputStream);
}

// Endpoint में usage:
// await DecodeStreamAsync(Request.Body, "uploaded-file.bin");
नोट:ASP.NET Core handlers में CopyTo से CopyToAsync पर switch करें। Request thread पर Synchronous I/O Kestrel में default रूप से blocked है और InvalidOperationException throw करता है।

C# में Base64 JWT Token Payload कैसे Decode करें

एक JWT में dots से separated तीन Base64url-encoded segments होते हैं। बीच वाला segment payload है। आप JWT library pull किए बिना इसे decode कर सकते हैं — . पर split करें, Base64url characters normalize करें, padding fix करें, और Convert.FromBase64String() call करें। यह लगभग सभी को पहली बार trip up करता है क्योंकि JWT + और / के बजाय - और _ उपयोग करता है, और = padding strip करता है।

C# (.NET 6+)
using System;
using System.Text;

static string DecodeJwtPayload(string token)
{
    string[] parts = token.Split('.');
    if (parts.Length != 3)
        throw new ArgumentException($"Invalid JWT: expected 3 segments, got {parts.Length}");

    // Payload लें (दूसरा segment)
    string payload = parts[1];

    // URL-safe characters को standard Base64 से replace करें
    payload = payload.Replace('-', '+').Replace('_', '/');

    // 4 के multiple तक Pad करें
    switch (payload.Length % 4)
    {
        case 2: payload += "=="; break;
        case 3: payload += "=";  break;
    }

    byte[] bytes = Convert.FromBase64String(payload);
    return Encoding.UTF8.GetString(bytes);
}

// Real-shaped token के साथ test करें
string token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9"
    + ".eyJzdWIiOiJ1c3ItNjcyIiwiaXNzIjoiYXV0aC5leGFtcGxlLmNvbSIsImV4cCI6MTc0MTk1NjgwMCwicm9sZXMiOlsiYWRtaW4iLCJiaWxsaW5nIl19"
    + ".SIGNATURE_PLACEHOLDER";

Console.WriteLine(DecodeJwtPayload(token));
// {"sub":"usr-672","iss":"auth.example.com","exp":1741956800,"roles":["admin","billing"]}

Quick note: यह केवल payload पढ़ता है। यह signature verify नहीं करता। Production auth validation के लिए, proper library जैसे Microsoft.IdentityModel.JsonWebTokens उपयोग करें। लेकिन debugging, logging, और test assertions के लिए, यह manual approach पर्याप्त है।

Decoded JWT payload को typed object में Parse करना

एक बार JSON string मिलने पर, string manipulation के बिना individual claims access करने के लिए इसे System.Text.Json से deserialize करें:

C# (.NET 6+)
using System;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

record JwtPayload(
    [property: JsonPropertyName("sub")] string Subject,
    [property: JsonPropertyName("iss")] string Issuer,
    [property: JsonPropertyName("exp")] long Expiration,
    [property: JsonPropertyName("roles")] string[] Roles
);

// ऊपर से DecodeJwtPayload() के बाद
string json = DecodeJwtPayload(token);
var claims = JsonSerializer.Deserialize<JwtPayload>(json)!;

Console.WriteLine($"User: {claims.Subject}");
Console.WriteLine($"Issuer: {claims.Issuer}");
Console.WriteLine($"Expires: {DateTimeOffset.FromUnixTimeSeconds(claims.Expiration):u}");
Console.WriteLine($"Roles: {string.Join(", ", claims.Roles)}");
// User: usr-672
// Issuer: auth.example.com
// Expires: 2025-03-14 12:00:00Z
// Roles: admin, billing

सामान्य गलतियाँ

मैंने production C# services में इनमें से हर एक गलती की है। पहली दो गलतियाँ सबसे common हैं — code reviews में Base64-related bugs का बड़ा हिस्सा इन्हीं से आता है। हर गलती अकेले देखें तो obvious लगती है, लेकिन जब किसी बड़े feature के बीच में फँसे हों और Base64 decoding pipeline में बस एक step हो तो इन्हें miss करना आसान है।

Input से whitespace strip करना भूलना

समस्या: Config files, environment variables, या user input से पढ़ी गई Base64 strings में अक्सर trailing newlines होते हैं। Convert.FromBase64String() Base64 alphabet के बाहर किसी भी character को reject करता है, जिसमें \r\n शामिल है।

समाधान: Decode करने से पहले whitespace strip करने के लिए .Trim() या .Replace() call करें।

Before · C#
After · C#
// Environment variable में trailing newline है
string encoded = Environment.GetEnvironmentVariable("DB_PASS_B64")!;
byte[] decoded = Convert.FromBase64String(encoded);
// FormatException: The input is not a valid Base-64 string
string encoded = Environment.GetEnvironmentVariable("DB_PASS_B64")!;
string cleaned = encoded.Replace("\n", "").Replace("\r", "").Trim();
byte[] decoded = Convert.FromBase64String(cleaned);
Console.WriteLine(Encoding.UTF8.GetString(decoded));
URL-safe Base64 पर Convert.FromBase64String() उपयोग करना

समस्या: JWT tokens और कुछ API payloads - और _ (URL-safe alphabet) उपयोग करते हैं। Standard decoder केवल + और / accept करता है — यह पहले - character पर FormatException throw करता है।

समाधान: Decode करने से पहले - को + से और _ को / से replace करें। Padding भी fix करें।

Before · C#
After · C#
// JWT payload — URL-safe Base64 उपयोग करता है
string payload = "eyJzdWIiOiJ1c3ItNjcyIn0";
byte[] decoded = Convert.FromBase64String(payload);
// FormatException
string payload = "eyJzdWIiOiJ1c3ItNjcyIn0";
payload = payload.Replace('-', '+').Replace('_', '/');
switch (payload.Length % 4)
{
    case 2: payload += "=="; break;
    case 3: payload += "="; break;
}
byte[] decoded = Convert.FromBase64String(payload);
Console.WriteLine(Encoding.UTF8.GetString(decoded));
// {"sub":"usr-672"}
Binary data को string में convert करना

समस्या: Decoded image या protobuf bytes पर Encoding.UTF8.GetString() call करने से garbage produce होता है। इससे भी बुरा, उस string को bytes में वापस convert करने से data चुपचाप corrupt हो जाता है क्योंकि invalid UTF-8 sequences replace हो जाते हैं।

समाधान: Binary data को अपनी पूरी pipeline में byte[] के रूप में रखें। GetString() केवल तब call करें जब आप जानते हों कि content text है।

Before · C#
After · C#
byte[] decoded = Convert.FromBase64String(pngBase64);
string imageStr = Encoding.UTF8.GetString(decoded); // binary corrupt करता है
File.WriteAllText("image.png", imageStr); // broken file
byte[] decoded = Convert.FromBase64String(pngBase64);
// Bytes directly write करें — कोई string conversion नहीं
File.WriteAllBytes("image.png", decoded);
Encoding specify न करना (platform behavior पर default करना)

समस्या: कुछ पुराने .NET Framework APIs system के current ANSI code page पर default करते हैं, जो machines के बीच vary करता है। Code page 1252 वाला Windows server और UTF-8 वाला Linux container same bytes से different strings produce करते हैं।

समाधान: हमेशा Encoding.UTF8 explicitly specify करें। Platform default पर कभी rely न करें।

Before · C#
After · C#
byte[] decoded = Convert.FromBase64String(encoded);
// Encoding.Default platforms के बीच vary करता है
string result = Encoding.Default.GetString(decoded);
byte[] decoded = Convert.FromBase64String(encoded);
string result = Encoding.UTF8.GetString(decoded);
// Windows, Linux, macOS पर consistent

Method Comparison

.NET में ज़्यादातर developers की सोच से कहीं ज़्यादा Base64 decoding methods हैं। नीचे की table हर built-in option plus दो सबसे common third-party alternatives cover करती है। "Allocation" column high-throughput services में सबसे अधिक मायने रखता है — हर call पर नया byte[] allocate करने वाला method tight loops में GC पर pressure डालता है।

मेथड
Allocation
Error Handling
Streaming
Custom Types
इंस्टॉल आवश्यक
Convert.FromBase64String()
New byte[]
FormatException
नहीं
नहीं
नहीं (.NET Framework 1.1+)
Convert.TryFromBase64String()
Caller Span
Returns false
नहीं
नहीं
नहीं (.NET 5+)
Convert.FromBase64CharArray()
New byte[]
FormatException
नहीं
नहीं
नहीं (.NET Framework 1.1+)
Base64.DecodeFromUtf8()
Caller Span
OperationStatus
आंशिक
नहीं
नहीं (.NET Core 2.1+)
Base64.DecodeFromUtf8InPlace()
In-place
OperationStatus
नहीं
नहीं
नहीं (.NET Core 2.1+)
CryptoStream + FromBase64Transform
Streaming buffer
Exception
हाँ
नहीं
नहीं (.NET Framework 2.0+)
BouncyCastle Base64
New byte[]
Exception
हाँ
नहीं
हाँ (NuGet)

रोज़मर्रा के काम के लिए: Convert.FromBase64String()। Hot paths के लिए जहाँ आप user input validate करते हैं: TryFromBase64String()। Raw request bytes पर operate करने वाले ASP.NET Core middleware के लिए: Base64.DecodeFromUtf8()। Large files के लिए: CryptoStream + FromBase64Transform। BouncyCastle तभी sense बनाता है जब यह already आपके dependency tree में अन्य cryptographic operations के लिए हो।

कुछ भी compile किए बिना quick verification के लिए, online Base64 decoder one-off console app लिखने से तेज़ है।

अक्सर पूछे जाने वाले प्रश्न

C# में Base64 string को text में कैसे डिकोड करें?

byte array पाने के लिए Convert.FromBase64String() कॉल करें, फिर उसे Encoding.UTF8.GetString() में पास करें। encoding वही होनी चाहिए जो encoding के समय उपयोग की गई थी — UTF-8 लगभग सभी आधुनिक सिस्टम के लिए सुरक्षित डिफ़ॉल्ट है। यदि इनपुट में whitespace या line breaks हो सकते हैं, तो डिकोड करने से पहले .Trim() कॉल करें या उन्हें हटा दें।

C# (.NET 6+)
using System;
using System.Text;

string encoded = "cG9zdGdyZXM6eGs5bVAycVI=";
byte[] bytes = Convert.FromBase64String(encoded);
string result = Encoding.UTF8.GetString(bytes);
Console.WriteLine(result);
// postgres:xk9mP2qR

Convert.FromBase64String() और Convert.TryFromBase64String() में क्या अंतर है?

FromBase64String() अमान्य इनपुट पर FormatException throw करता है। TryFromBase64String() एक bool लौटाता है और result को caller-provided Span<byte> में लिखता है, जिससे यह hot paths के लिए उपयुक्त है जहाँ आप exception overhead से बचना चाहते हैं। TryFromBase64String() के लिए .NET 5 या बाद का version आवश्यक है।

C# (.NET 6+)
using System;

string input = "maybe-not-valid-base64!!";
Span<byte> buffer = stackalloc byte[256];

if (Convert.TryFromBase64String(input, buffer, out int written))
    Console.WriteLine($"Decoded {written} bytes");
else
    Console.WriteLine("Invalid Base64 input");

C# में Base64url JWT payload को कैसे डिकोड करें?

Token को dots पर split करें, दूसरा segment लें, - को + से और _ को / से बदलें, = से 4 के multiple तक pad करें, फिर Convert.FromBase64String() कॉल करें। JWT tokens URL-safe Base64 alphabet उपयोग करते हैं, जिसे .NET का standard decoder सीधे handle नहीं करता।

C# (.NET 6+)
string token = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c3ItNjcyIn0.SIG";
string payload = token.Split('.')[1];
payload = payload.Replace('-', '+').Replace('_', '/');
switch (payload.Length % 4)
{
    case 2: payload += "=="; break;
    case 3: payload += "="; break;
}
byte[] bytes = Convert.FromBase64String(payload);
Console.WriteLine(Encoding.UTF8.GetString(bytes));
// {"sub":"usr-672"}

C# में Base64 डिकोड करते समय सही Encoding कैसे चुनें?

डिफ़ॉल्ट के रूप में Encoding.UTF8 उपयोग करें — यह ASCII और multi-byte Unicode characters को handle करता है। Encoding.ASCII केवल तब उपयोग करें जब आपको पूरा यकीन हो कि data pure 7-bit ASCII है। Encoding.Unicode (.NET में UTF-16LE है) केवल तब उपयोग करें जब मूल data UTF-16 के रूप में encode किया गया था, जो कभी-कभी Windows-internal strings और PowerShell exports के साथ होता है।

Convert.FromBase64String() FormatException क्यों throw करता है?

तीन सामान्य कारण: इनपुट में whitespace या line breaks हैं (डिकोड करने से पहले हटाएँ), इनपुट URL-safe characters जैसे - और _ उपयोग करता है (इन्हें क्रमशः + और / से बदलें), या padding गलत या अनुपस्थित है (padding के बाद कुल लंबाई 4 का multiple होनी चाहिए)। Java के विपरीत, .NET में कोई built-in MIME decoder नहीं है जो whitespace tolerate करे — आपको इनपुट स्वयं साफ़ करना होगा या CryptoStream के साथ FromBase64Transform और IgnoreWhiteSpaces mode उपयोग करना होगा।

C# (.NET 6+)
// Whitespace ठीक करें
string cleaned = rawInput.Replace("\n", "").Replace("\r", "").Trim();
byte[] decoded = Convert.FromBase64String(cleaned);

क्या C# में बड़े Base64 data को stream-decode किया जा सकता है?

हाँ। System.Security.Cryptography से FromBase64Transform के साथ एक CryptoStream उपयोग करें। यह chunks में decode करता है जैसे-जैसे आप पढ़ते हैं, इसलिए file size की परवाह किए बिना memory flat रहती है। यदि इनपुट में line breaks हैं तो FromBase64TransformMode.IgnoreWhiteSpaces पास करें। .NET 6+ पर, manual chunked processing के लिए Base64.DecodeFromUtf8() के साथ IAsyncEnumerable pattern भी उपयोग किया जा सकता है, हालांकि file-to-file decoding के लिए CryptoStream सरल है।

C# (.NET 6+)
using System.IO;
using System.Security.Cryptography;

using var input = File.OpenRead("payload.b64");
using var transform = new FromBase64Transform();
using var cryptoStream = new CryptoStream(input, transform, CryptoStreamMode.Read);
using var output = File.Create("payload.bin");
cryptoStream.CopyTo(output);

संबंधित Tools

  • Base64 Encoder — browser में text या binary data को Base64 में encode करें, C# unit tests में paste करने के लिए test fixtures generate करने के लिए उपयोगी।
  • JWT Decoder — तीनों JWT segments को एक साथ decode और inspect करें, field-by-field payload inspection के साथ — जब आपको केवल token पढ़ना हो तो C# helper लिखने से तेज़।
  • URL Decoder — URL-encoded strings को percent-decode करें, जब API responses Base64url data को percent-encoded query parameters के साथ mix करते हों तब उपयोगी।
  • JSON Formatter — Base64 JWT payload या API config decode करने के बाद, JSON यहाँ paste करें structure pretty-print और validate करने के लिए।
इसमें भी उपलब्ध:JavaScriptPythonGoJava
AP
Alexei PetrovGame Developer & Unity Engineer

Alexei is a game developer who has shipped multiple titles using Unity and C#. He focuses on gameplay systems, runtime performance, and the serialisation and data-management patterns unique to game development. He writes about Unity scripting, C# async/await in game contexts, asset serialisation, binary data handling, and the intersection of game engineering and general software craftsmanship.

ER
Emma Richardsonतकनीकी समीक्षक

Emma is a .NET developer and cloud engineer who builds production APIs and backend services with ASP.NET Core and Azure. She has worked on everything from microservice migrations to real-time SignalR applications. She writes about C# language features, the System.Text.Json and Newtonsoft.Json ecosystems, Azure integrations, and the architectural patterns that make .NET services scalable and maintainable.