简体   繁体   English

如何将MemoryStream从Google Drive获取请求转换为XML文件C#?

[英]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. 我正在.Net Core 2中工作,并且正在使用Google驱动器v3 API并获取XML文件。 I get back a MemoryStream but am unable to read the MemoryStream to an XmlDocument. 我取回MemoryStream,但是无法将MemoryStream读取到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? 如何将MemoryStream转换为XmlDocument? Or string that I can parse to XML? 还是我可以解析为XML的字符串?

I have tried loading the stream to an xml document and a text reader. 我尝试将流加载到xml文档和文本阅读器。 The text reader comes back with an empty string and the xml loader says parent node not found. 文本阅读器返回一个空字符串,并且xml加载器显示未找到父节点。

//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. 对于XmlDocument ,听起来好像没有一点点按摩就可能不是有效的XML,因此您应该从基于MemoryStream的实现开始,以查看从服务中获取的内容。

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. 流具有像光标一样的“当前位置”的概念,而传统的Download类的方法在将光标加载到流中之后将光标留在数据的末尾。 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) . 有时这无关紧要,例如当您使用FileStream将数据直接写到文件中时,但是如果要将数据加载到MemoryStream然后想立即读取它,则需要先重置游标使用stream.Seek(0, SeekOrigin.Begin)返回到流的开头。

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

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