vb.net 编码/解码字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13488394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enocde/Decode string
提问by MojoDK
(using vb.net)
(使用 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...
我有一个 ini 文件,我需要将一个 RTF 文件作为 ini 文件中的一行发布 - 比如...
[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?
为避免 RTF 文件中的换行符、特殊代码等包装在 ini 文件中,我如何将其编码(和解码)为单个字符串?
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?
如果有一个函数可以将字符串(在我的情况下是 RTF 文件的内容)转换为一行数字,然后将其解码回来?
What would you do?
你会怎么办?
Thanks!
谢谢!
采纳答案by fixagon
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.
您可以使用 base64 编码对它们进行编码。就像内容被处理为二进制一样 --> 它可以是任何类型的文件。但是当然在配置文件中您将无法读取文件的内容。
Here a Snippet to Base64 encode / decode
这里是 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));
}
and in VB.NET:
在 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

