简体   繁体   English

在C#中从Base64解码

[英]Decoding from Base64 in C#

I created XML Document and saved this document as 我创建了XML Document并将此文档保存为

  XmlDocument xmlDoc = new XmlDocument();
  XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
  xmlDoc.AppendChild(dec);
  XmlTextWriter writer = new XmlTextWriter(fullPath,Encoding.UTF8);
  writer.Formatting = Formatting.Indented;
  xMLDoc.Save(writer);
  writer.Flush();

And then I have encoded this document using Base64 Encoder 然后我使用Base64 Encoder编码了这个文档

The Decoder could not parse XML file. 解码器无法解析XML文件。 I created the decoder myself and got this result 我自己创建了解码器并得到了这个结果

 ?<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<ClinicalDocument 
 xmlns=\"urn:hl7-org:v3\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
classCode=\"DOCCLIN\" moodCode=\"EVN\" schemaLocation=\"urn:hl7-org:v3
CDA.xsd\">\r\n  <typeId extension=\"POCD_HD000040\" root=\"2.16.840.1.113883.1.3
\" />\r\n

Please help me to resolve the issue. 请帮我解决这个问题。 How I have to save the XML file to avoid the issues? 我如何保存XML文件以避免问题? Or How I have to encode to Base 64 to resolve the issue? 或者我如何编码到Base 64来解决问题? I am using base64 encoder to encode xml file. 我使用base64编码器来编码xml文件。 I am requesting document. 我要求提供文件。 it is required to use base64 encoder. 它需要使用base64编码器。 I decoded myself to check where is the problem. 我解码自己检查问题在哪里。 The decoder is Java . 解码器是Java。 They can not parse the xml file I believe because ?< in front of the document. 他们无法解析我认为的xml文件,因为?<在文档前面。

It depends on how you're encoding it, but you should use UTF-8 since the document is declared as such. 这取决于你如何编码它,但你应该使用UTF-8,因为文档是这样声明的。 Here are examples for encoding and decoding: 以下是编码和解码的示例:

See Jon Skeet's answer here: 请参阅Jon Skeet的回答:
C# base64 encoding/decoding with serialization of objects issue C#base64编码/解码与对象序列化问题

To encode: 编码:

public string EncodeStringToBase64(string stringToEncode)
{
    return Convert.ToBase64String(Encoding.UTF8.GetBytes(stringToEncode));
}

To decode: 要解码:

public string DecodeStringFromBase64(string stringToDecode)
{       
    return Encoding.UTF8.GetString(Convert.FromBase64String(stringToDecode));
}

One other option - could be BOM in default Utf-8 stream created by new XmlTextWriter(fullPath,Encoding.UTF8); 另一个选项 - 可能是由新的XmlTextWriter(fullPath,Encoding.UTF8)创建的默认Utf-8流中的BOM;

Consider using second constructor for UTF8 - http://msdn.microsoft.com/en-us/library/s064f8w2.aspx that does not insert BOM into the stream. 考虑使用UTF8的第二个构造函数 - http://msdn.microsoft.com/en-us/library/s064f8w2.aspx ,它不会将BOM插入流中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM