---
title: "How do I encode and decode a base64 string in C#?"  
description: "How do I encode and decode a base64 string in C#?"  
author: "Steilla Mitchel"  
published: 2023-07-12  
updated: 2023-07-13  
canonical: https://www.mindstick.com/forum/159053/how-do-i-encode-and-decode-a-base64-string-in-c-sharp  
category: "c#"  
tags: ["c#", "string"]  
reading_time: 2 minutes  

---

# How do I encode and decode a base64 string in C#?

How do I [encode](https://www.mindstick.com/blog/51/encode-and-decode-in-dot-net) and decode a base64 [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) in C#?

## Replies

### Reply by Aryan Kumar

Sure, here is how to encode and decode a base64 string in C#:

## Encoding a string to base64

To encode a string to base64, you can use the `Convert.ToBase64String()` method. This method takes a byte array as a parameter and returns a base64 encoded string.

For example, the following code encodes the string "Hello, world!" to base64:

C#

```plaintext
string myString = "Hello, world!";

byte[] myBytes = Encoding.UTF8.GetBytes(myString);

string base64String = Convert.ToBase64String(myBytes);
```

## Decoding a base64 string

To decode a base64 string, you can use the `Convert.FromBase64String()` method. This method takes a base64 encoded string as a parameter and returns a byte array.

For example, the following code decodes the base64 string "SGVsbG8gV29ybGQh" to the string "Hello, world!":

C#

```plaintext
string base64String = "SGVsbG8gV29ybGQh";

byte[] myBytes = Convert.FromBase64String(base64String);

string myString = Encoding.UTF8.GetString(myBytes);
```

Here is a complete example of how to encode and decode a base64 string in C#:

C#

```plaintext
using System;
using System.Text;

public class Base64EncodeDecode
{
    public static void Main(string[] args)
    {
        // Encode a string to base64.
        string myString = "Hello, world!";
        byte[] myBytes = Encoding.UTF8.GetBytes(myString);
        string base64String = Convert.ToBase64String(myBytes);

        // Decode a base64 string.
        string decodedString = Convert.FromBase64String(base64String);

        // Print the decoded string.
        Console.WriteLine(decodedString);
    }
}
```


---

Original Source: https://www.mindstick.com/forum/159053/how-do-i-encode-and-decode-a-base64-string-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
