简体   繁体   中英

How do I convert the MemoryStream from a Google Drive Get request to an XML File C#?

I am working in .Net Core 2 and I am using the google drive v3 API and fetching an XML file. I get back a MemoryStream but am unable to read the MemoryStream to an XmlDocument. I have tried a couple files and the size of the memory stream matches the file size so I am confident I am acutally getting the data. How do I turn that MemoryStream into an XmlDocument? Or string that I can parse to XML?

I have tried loading the stream to an xml document and a text reader. The text reader comes back with an empty string and the xml loader says parent node not found.

//Fetch the file from Google Drive
var request = _driveService.Files.Get(fileId);
var stream = new System.IO.MemoryStream();
request.Download(stream);

//How I Try and parse to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();

//How I try to load to xml
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(stream);

For the XmlDocument , it sounds like what you're getting back may not be valid XML without a little massaging, so you should start with the MemoryStream -based implementation to see what you're getting from the service.

To get that working, you need to "rewind" the stream. Streams have a concept of "current position", like a cursor, and methods like Download traditionally leave the cursor at the end of the data after loading it into the stream. Sometimes this doesn't matter, like when you're using a FileStream to write the data directly to a file, but if you're loading the data into a MemoryStream and then want to immediately read it, you need to first reset the cursor back to the beginning of the stream with stream.Seek(0, SeekOrigin.Begin) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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