Overview
String manipulation and conversion are common tasks in C# development. Being able to convert strings to different formats such as JSON, Base64, XML, and CSV is essential for data interchange and integration. This article will explore how to convert strings to these formats and vice versa in C#, providing examples for each conversion.
Converting String to JSON
JSON (JavaScript Object Notation) is a popular data interchange format. C# provides libraries that make it easy to convert strings to JSON using the System.Text.Json or Newtonsoft.Json libraries.
In the below code example, we parse the input string using JsonDocument.Parse, and then use JsonSerializer.Serialize to convert the parsed document to a JSON string. This allows us to manipulate and serialize the JSON data as needed.
public static string StringToJson(string JsonString) {
// Convert string to JSON
JsonDocument jsonDocument = JsonDocument.Parse(JsonString);
return JsonSerializer.Serialize(jsonDocument.RootElement);
}
Console.WriteLine("Converting String to Json");
Console.WriteLine(ZR.CodeExample.Convert.StringToJson("{\"name\":\"John\",\"age\":30}"));
Converting JSON to String
Converting JSON back to a string in C# involves deserializing the JSON data using the appropriate JSON library.
In the example code below, we parse the JSON string using `JsonDocument.Parse` and retrieve the raw text representation of the JSON using `GetRawText()` on the root element. This gives us the original JSON string.
public static string JsonToString(string JsonString) {
// Convert JSON to string
JsonDocument jsonDocument = JsonDocument.Parse(JsonString);
return jsonDocument.RootElement.GetRawText();
}
Console.WriteLine("Converting Json to String");
Console.WriteLine(ZR.CodeExample.Convert.StringToJson("{\"name\":\"Lisa\",\"age\":25}"));
Converting String to Base64
Base64 encoding is used to convert binary data into a text format. C# provides built-in functions to convert strings to Base64 using the System.Convert class.
In the below code example, we convert the input string to a byte array using Encoding.UTF8.GetBytes method. Then, we use Convert.ToBase64String to convert the byte array to a Base64-encoded string.
public static string StringToBase64(string Base64String) {
// Convert string to Base64
byte[] bytes = Encoding.UTF8.GetBytes(Base64String);
return System.Convert.ToBase64String(bytes);
}
Console.WriteLine("Converting String to Base64");
Console.WriteLine(ZR.CodeExample.Convert.StringToBase64("I am Ziggy Rafiq and proud to write Articles for C# Corner. I work for Capgemini."));
Converting Base64 to String
To convert a Base64-encoded string back to its original form, we can use the `Convert.FromBase64String` method in C#.
In the below code example, we use Convert.FromBase64String to convert the Base64 string back to a byte array. Then, we use Encoding.UTF8.GetString to decode the byte array into the original string representation.
public static string Base64ToString(string Base64String) {
// Convert Base64 to string
byte[] bytes = System.Convert.FromBase64String(Base64String);
return Encoding.UTF8.GetString(bytes);
}
Console.WriteLine("Converting Base64 to String");
//Base64 Output value: I am Ziggy Rafiq and proud to write Articles for C# Corner. I work for Capgemini.
Console.WriteLine(ZR.CodeExample.Convert.Base64ToString("SSBhbSBaaWdneSBSYWZpcSBhbmQgcHJvdWQgdG8gd3JpdGUgQXJ0aWNsZXMgZm9yIEMjIENvcm5l\r\nci4gSSB3b3JrIGZvciBDYXBnZW1pbmku"));
Converting String to XML
XML (eXtensible Markup Language) is a widely used format for storing and exchanging data. C# provides the System.Xml namespace, which offers functionality for working with XML.
In the below code example, we create an instance of XmlDocument and load the input string using LoadXml. This parses the XML string and allows us to manipulate and work with the XML data. The OuterXml property returns the XML string representation.
public static string StringToXml(string XmlString) {
// Convert string to XML
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(XmlString);
return xmlDocument.OuterXml;;
}
Console.WriteLine("Converting String to XML");
Console.WriteLine(ZR.CodeExample.Convert.StringToXml("<root><name>John</name><age>30</age></root>"));
Converting XML to String
Converting XML back to a string involves manipulating the XML data using the System.Xml namespace.
In the code example below, we create an instance of XmlDocument and load the XML string using LoadXml. Then, we retrieve the OuterXml property, which gives us the original XML string representation.
public static string XmlToString(string XmlString) {
// Convert XML to string
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(XmlString);
return xmlDocument.OuterXml;
}
Console.WriteLine("Converting XML to String");
Console.WriteLine(ZR.CodeExample.Convert.XmlToString("<root><name>Peter</name><age>40</age></root>"));
Converting String to CSV
CSV (Comma-Separated Values) is a common file format for tabular data. To convert a string to CSV format, we can use the System.Text.StringBuilder class in C#.
In the code example below, we split the input string into lines using Split('\n') and then split each line into values using Split(','). We use a StringBuilder to construct the CSV string, appending the values with commas and a newline character. Finally, we obtain the CSV string using ToString().
public static string StringToCsv(string CsvString) {
// Convert string to CSV
StringBuilder csvBuilder = new StringBuilder();
foreach(string line in CsvString.Split('\n')) {
string[] values = line.Split(',');
csvBuilder.AppendLine(string.Join(",", values));
}
return csvBuilder.ToString();
}
Console.WriteLine("Converting String to CSV");
Console.WriteLine(ZR.CodeExample.Convert.StringToCsv("John,Smith,30\nJane,Doe,25"));
Converting CSV to String
Converting CSV back to a string involves parsing and manipulating the CSV data using the System.Text.StringBuilder class.
In the code below, we split the CSV string into lines using Split('\n'), then split each line into values using Split(','). We use a StringBuilder to construct the original string by appending the values with commas and a newline character.
public static string CsvToString(string CsvString) {
// Convert CSV to string
StringBuilder stringBuilder = new StringBuilder();
foreach(string line in CsvString.Split('\n')) {
string[] values = line.Split(',');
stringBuilder.AppendLine(string.Join(",", values));
}
return stringBuilder.ToString();
}
Console.WriteLine("Converting CSV to String");
Console.WriteLine(ZR.CodeExample.Convert.CsvToString("Lisa,Smith,25\nMike,Doe,47"));
Summary
Converting strings to different formats and vice versa is a common requirement in C# development. In this article, we explored examples of how to convert strings to JSON, Base64, XML, and CSV, as well as reverse conversions. We can easily perform these conversions in our C# applications by leveraging the provided libraries and techniques, enabling interoperability and data manipulation across various formats.
We can access the code examples in this article on Ziggy Rafiq GitHub Repo https://github.com/ziggyrafiq/CSharpStringConversionReverse and please do not forget to follow Ziggy Rafiq on LinkedIn https://www.linkedin.com/in/ziggyrafiq/ and click the link button if you have found this article useful or helpful.