Convert a file . pdf or . P7s to Base64 in C#

Asked

Viewed 1,215 times

2

I want to convert a file . pdf or . P7s to Base64 in C# which should be loaded in XML. How can I do?

EX:

<conteudoArquivoP7S>
    MIMCmfgGCSqGSIb3DQEHAqCDApnoMIMCmeMCAQExCzAJBgUrDgMCGgUAMIMCexwGCSqGSIb3DQEHAaCDAnsMBIMCewclUERGLTEuMgolZGhpOWhrbGZycDI1CqB5AgAEAAAACwAAAAZ7AgAKMSAwIG9iago8PAovUHJvZHVjZXIgKCkKPj4KZW5kb2JqCjIgMCBvYmoKPDwKL1R5cGUgL0NhdGFsb2cKL1BhZ2VzIDMgMCBSCj4+CmVuZG9iago0IDAgb2JqCjw8Ci9UeXBlIC9QYWdlCi9NZWRpYUJveCBbIDAgMCA2MTIgODQzIF0KL1BhcmVudCAzIDAgUgovUmVzb3VyY2VzIDw8Ci9YT2JqZWN0IDw8Ci9JbTEgNyAwIFIKPj4KL1Byb2NTZXQgWyAvUERGIC9JbWFnZUMgXQo+PgovQ29udGVudHMgNSAwIFIKPj4KZW5kb2JqCjUgMCBvYmoKPDwKL0xlbmd0aCA2IDAgUgo+PgpzdHJlYW0KcQo2MTIgMCAwIDg0MyAwIDAgY20KL0ltMSBEbwpRCmVuZHN0cmVhbQplbmRvYmoKNiAwIG9iagozMAplbmRvYmoKOSAwIG9iago8PAovTGVuZ3RoIDEwIDAgUgoKPj4Kc3RyZWFtCkEKZW5kc3RyZWFtCmVuZG9iagoxMCAwIG9iagoxCmVuZG9iago3IDAgb2JqCjw8Ci9UeXBlIC9YT2JqZWN0Ci9TdWJ0eXBlIC9JbWFnZQovTmFtZSAvSW0xCi9XaWR0aCA4NTAKL0hlaWdodCAxMTcwCi9CaXRzUGVyQ29tcG9uZW50IDgKL0xlbmd0aCA4IDAgUgovQ29sb3JTcGFjZSAvRGV2aWNlUkdCCi9GaWx0ZXIgWyAgL0RDVERlY29kZSBdCj4+CnN0cmVhbQr/2P/gABBKRklGAAEAAQAAAAAAAP/+AB9MRUFEIFRlY2hub2xvZ2llcyBJbmMuIFYxLjAxAP/bAIQAEhISHRQdLRsbLS0gICAtMSsrK
</conteudoArquivoP7S>

1 answer

3

A generic Base64 file encoding code should solve:

using (var fs = new FileStream("C:\\Caminho\\Do\\Arquivo.pdf", FileMode.Open, FileAccess.Read)) 
{
    byte[] bytesArquivo = new byte[fs.Length];
    fs.Read(bytesArquivo, 0, Convert.ToInt32(fs.Length));
    string stringEmBase64 = Convert.ToBase64String(bytesArquivo); 
}

To make the XML, use the class XmlOutput of Mark Rasmussen. I made her a Nuget package. The use is like this:

var xo = new XmlOutput()
    .XmlDeclaration()
    .Node("conteudoArquivoP7S").InnerText(stringEmBase64);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.