I'm using XmlReader to parse a XML document. One of the nodes contains base64 encoded data and I want to decode it. This is what I do:
byte[] buffer = new byte[4096];
int readBytes = 0;
using (FileStream outputFile = File.OpenWrite (path))
using (BinaryWriter bw = new BinaryWriter (outputFile)) {
while ((readBytes = reader.ReadElementContentAsBase64 (buffer, 0, 4096)) > 0) {
bw.Write (buffer, 0, readBytes);
}
}
But the file is empty and has a file size of 0 kB. I also tried this without success:
byte[] buffer = new byte[4096];
int readBytes = 0;
FileStream outputFile = new FileStream (path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
BinaryWriter bw = new BinaryWriter (outputFile);
while ((readBytes = reader.ReadElementContentAsBase64 (buffer, 0, 4096)) > 0) {
bw.Write (buffer, 0, readBytes);
}
outputFile.Close ();
I don't understand it. readBytes isn't empty so the data is here. If I temporary save the stream as file and convert it then it works (so I don't use ReadElementContentAsBase64
). I'm using Xamarin Studio on Mac for this and this code is embedded into a dll.
Am I doing something wrong or is this a bug? I had the problem that the decoding doesn't work correctly, but an empty file? What can be the reason for this? What can I check for?
Edit:
Now I tried it without the BinaryWriter
, but the file has still a size of 0 kB. Here you can see the implementation with the reader:
public async string CallWS(string path, CancellationToken cancelToken)
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(someXMLDoc);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(webserviceAddress);
webRequest.Headers.Add("SOAPAction", "http://schemas.xmlsoap.org/soap/envelope");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
using (Stream stream = webrequest.GetRequestStream())
{
soapEnvelop.Save(stream);
}
using (var response = await webRequest.GetResponseAsync ())
using (Stream stream = response.GetResponseStream ())
return parser.GetDocument(stream, path);
}
public string GetDocument(Stream stream, string path)
{
// read xml and save file
using (XmlReader reader = XmlReader.Create(stream))
{
while (reader.Read())
{
if (reader.IsStartElement() && reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "Document":
reader.ReadToDescendant("cKey");
string ckey = reader.ReadInnerXml();
switch (ckey)
{
case "base64Content":
reader.ReadToNextSibling("cValue");
byte[] buffer = new byte[4096];
int readBytes = 0;
using (FileStream outputFile = File.OpenWrite(path))
{
while ((readBytes = reader.ReadElementContentAsBase64(buffer, 0, 4096)) > 0)
{
outputFile.Write(buffer, 0, readBytes);
}
}
break;
default:
break;
}
break;
default:
break;
}
}
}
}
return path;
}