UiPath Studio - How to convert a System.String variable into a Base64String and decode a Base64String into a System.String variable?
Issue Description
Multiple reasons can result in a need to convert strings to Base64 and vice versa in UiPath Studio:
- Secure Data Transfer: Base64 encoding helps in providing a secure way of transferring data. It encodes the data into string format which can be easily transferred without loss or modification of data.
- Handling Binary Data: Base64 encoding is specially designed to handle binary data and make sure it can be manipulated and used like text data. For example, if there is a need to send binary files over email, they need to be Base64 encoded.
- Integration with APIs: Some APIs require data in Base64 format, so they need to be converted from strings to Base64.
- Data Privacy and Security: In some cases, sensitive data like password strings can be converted into Base
Resolution
This conversion can be done in UiPath Studio using VB.NET language support with the help of the UiPath.System.Activities package:
In this example, the initial System.String variable (for example StringValue) has the value "Hello World!":
System.String to Base64String
Create a new System.String variable (for example StringValueToBase64) with this expression
Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(StringValue))
Here's a step-by-step explanation:
-
System.Text.Encoding.UTF8.GetBytes(StringValue)
: UTF8 is a text encoding scheme that represents every character in the Unicode standard. This method transforms theStringValue
, which is a regular string in your code, into an array of bytes. This conversion is done so that the function works with the digital or binary representation of your string. -
Convert.ToBase64String(...)
: This function takes an array of bytes and converts it to a Base64 string. Base64 encoding schemes are used when binary data needs to be stored and transferred over media that are designed to deal with text data.
Base64String to System.String
Create a new System.String variable (for example DecodeBase64Value) with this expression:
System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(StringValueToBase64))
Here's a step-by-step explanation:
-
Convert.FromBase64String(StringValueToBase64)
: This method converts a Base64 string (StringValueToBase64) back into a byte array. It's reverse functionality toConvert.ToBase64String()
. This is because a Base64 encoded string is essentially binary data that has been translated into a textual format. -
System.Text.Encoding.UTF8.GetString(...)
: This takes the byte array generated by the previous method and converts it back into a string, using the UTF8 encoding.
Results for running the below expression in a Log Message activity:
"Original String Value: " + StringValue + vbCr + "Base64 encoded value: " + StringValueToBase64 + vbCr + "Base64 decoded value: " + DecodeBase64Value