Loading the downloaded xml file into an XmlDocument object

In any case, I try to download the file from the browser and then read it in the XmlDocument object on the server. I originally hacked this by saving the file to disk, reading it in the XmlDocument object, and deleting the file. The only problem was that the delete action was attempted before the XmlDocument.Load action was completed. In any case, this seemed an ugly decision, so it was happily abandoned.

The next effort was to read directly from Request.Files[x].InputStream directly into the XmlDocument, but I am having problems. The following code does not work with

"No root element"

I know that XML is valid, so it must be something else.

 foreach (string file in Request.Files) { HttpPostedFileBase postedFile = Request.Files[file] as HttpPostedFileBase; if (postedFile.ContentLength > 0) //if file not empty { //create an XML object and load it in XmlDocument xmlProjPlan = new XmlDocument(); Stream fileStream = postedFile.InputStream; byte[] byXML = new byte[postedFile.ContentLength]; fileStream.Read(byXML, 0, postedFile.ContentLength); xmlProjPlan.Load(fileStream); } } 

+4
source share
2 answers

Here is an example:

 <% using (Html.BeginForm("index", "home", FormMethod.Post, new { enctype = "multipart/form-data" })) { %> <input type="file" name="file" /> <input type="submit" value="Upload" /> <% } %> 

And the action of the controller:

 [HttpPost] public ActionResult Index(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0 && file.ContentType == "text/xml") { var document = new XmlDocument(); document.Load(file.InputStream); // TODO: work with the document here } return View(); } 
+9
source

So, some things look wrong.

 fileStream.Read(byXML, 0, postedFile.ContentLength); 

This line reads the file into the byXML byte buffer, but later you do not use this byte buffer, so I think you wanted to delete this line or use the byXML buffer for your XmlDocument.Load () instead of fileStream.

This line, unfortunately, pushes your thread to the end, so when you call

 xmlProjPlan.Load(fileStream); 

He does not receive anything, because the flow is already at the end. This is probably why he cannot find the root element.

+4
source

All Articles