编码/解码字符串

5

(使用vb.net)

你好,

我有一个ini文件,需要将RTF文件作为单行发布到ini文件中,例如...

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

为了避免RTF文件中的换行符、特殊代码等内容在ini文件中自动换行,我该如何将其编码(和解码)为单个字符串?
我在想是否有一种将字符串(在我的情况下是RTF文件的内容)转换为数字行再进行解码的函数?
你会怎么做?
谢谢!
2个回答

6
你可以使用Base64编码将它们编码。这样,内容会被视为二进制 --> 它可以是任何类型的文件。 但是在配置文件中,你将无法读取文件的内容。
下面是一个Base64编码/解码代码片段:
//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));
}

在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

+1,但我想提一下在编码之前压缩文件的可能性,因为Base64会增加33%的大小。而且...这是VB而不是C# ;) - igrimpe

-1
使用此函数解码Base64编码的字符串:
Private Function DecodeBase64(ByVal Base64Encoded)
    Return System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(Base64Encoded))
End Function

如果不起作用,请尝试在解码之前在Base64编码字符串末尾添加“=”或“==”以匹配其长度。

问题在三个地方提到需要有编码和解码函数。 - Enigmativity

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接