Tuesday, July 27, 2010

'Steam'lining the upload

Afternoon,

Turns out yesterday's approach to get the uploaded XML file into the XmlDocument object was a bad idea, which doesn't come as a surprise. It was simply the only way I could make it work at the time.
However, the XmlDocument.Load operation had not completed before I tried to delete the XML file from disk causing conflict errors. As this was the smallest possible MS Project XML file, this was clearly a non-starter.

I've returned to the original idea of reading the file straight into the XmlDocument object from the Request.Files[x].InputStream. Which I didn't know existed yesterday...

Here is the new code for the method:

HttpPost, ActionName("AddProjectPlan")] //don't really understand this?

public void Add()

{

foreach (string file in Request.Files) //only posting one element from the form, but this would work for many

{

HttpPostedFileBase postedFile = Request.Files[file] as HttpPostedFileBase;

if (postedFile.ContentLength > 0) //if file not empty

{

//create an XML object for loading in the project plan xml

XmlDocument xmlProjPlan = new XmlDocument();

try

{

xmlProjPlan.Load(postedFile.InputStream);

Response.Write("File " + postedFile.FileName + " successfully loaded
"
);

}

catch

{

Response.Write("File " + postedFile.FileName + " is not valid XML
"
);

}

//Response.Write(xmlProjPlan.InnerXml); //for debugging

}

else

{

// Let user know there was a problem

Response.Write("No file submitted or file zero length");

}

}

}

}



The problem was solved by some good people at StackOverflow, question and answer here:

No comments:

Post a Comment