MojoDK
MojoDK

Reputation: 4538

Enocde/Decode string

(using vb.net)

Hi,

I have an ini file where I need to post an RTF file as a single line in the ini file - like...

[my section]
rtf_file_1=bla bla bla (the content of the rtf file)

To avoid linebreaks, special codes etc. in the RTF file from wrapping in the ini file, how can I encode (and decode) it as a single string?

I was thing if there was a function to convert a string (in my case the content of the RTF file) into a line of numbers and then decode it back?

What would you do?

Thanks!

Upvotes: 5

Views: 24775

Answers (2)

Stefan Đorđević
Stefan Đorđević

Reputation: 595

Use this function to decode Base64 encoded string:

Private Function DecodeBase64(ByVal Base64Encoded)
    Return System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(Base64Encoded))
End Function

If it doesn't work, try adding "=" or "==" at the end of Base64 encoded string before decoding to match its length.

Upvotes: -1

fixagon
fixagon

Reputation: 5566

You can encode them using base64 encoding. Like that the content gets treated binary --> it can be any type of file. But of course in the config file you wont be able to read the content of the file.

Here a Snippet to Base64 encode / decode

//Encode
string filePath = "";
string base64encoded = null;
using (StreamReader r = new StreamReader(File.OpenRead(filePath)))
{
    byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(r.ReadToEnd());
    base64encoded = System.Convert.ToBase64String(data);
}

//decode --> write back
using(StreamWriter w = new StreamWriter(File.Create(filePath)))
{
    byte[] data = System.Convert.FromBase64String(base64encoded);

    w.Write(System.Text.ASCIIEncoding.ASCII.GetString(data));
}

and in VB.NET:

    Dim filePath As String = ""
    Dim base64encoded As String = vbNull

    'Encode()
    Using r As StreamReader = New StreamReader(File.OpenRead(filePath))
        Dim data As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(r.ReadToEnd())
        base64encoded = System.Convert.ToBase64String(data)
    End Using

    'decode --> write back
    Using w As StreamWriter = New StreamWriter(File.Create(filePath))
        Dim data As Byte() = System.Convert.FromBase64String(base64encoded)
        w.Write(System.Text.ASCIIEncoding.ASCII.GetString(data))
    End Using

Upvotes: 6

Related Questions