5

(使用 vb.net)

你好,

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

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

为避免 RTF 文件中的换行符、特殊代码等包含在 ini 文件中,如何将其编码(和解码)为单个字符串?

如果有一个函数可以将字符串(在我的情况下是 RTF 文件的内容)转换为一行数字,然后将其解码回来,那我是怎么回事?

你会怎么办?

谢谢!

4

2 回答 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
于 2012-11-21T07:54:12.843 回答
-1

使用此函数解码 Base64 编码的字符串:

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

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

于 2020-08-21T23:57:41.573 回答