c# - 将上传的 xml 文件加载到 XmlDocument 对象中

标签 c# asp.net asp.net-mvc

无论如何,我正在尝试从浏览器上传文件,然后将其读入服务器上的 XmlDocument 对象。最初我通过将文件保存到磁盘、将其读入 XmlDocument 对象然后删除文件来破解此问题。唯一的问题是删除操作试图在 XmlDocument.Load 操作完成之前发生。 无论如何,这感觉像是一个丑陋的解决方案,所以它很高兴地被放弃了。

接下来的工作是直接从 Request.Files[x].InputStream 读取到 XmlDocument,但我遇到了问题。 以下代码失败并显示

'Root element is missing'

我知道 XML 是有效的,所以它一定是其他东西。

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);
     }
}

最佳答案

这是一个例子:

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

Controller Action :

[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();
}

关于c# - 将上传的 xml 文件加载到 XmlDocument 对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3342998/

相关文章:

c# - 在奇怪的情况下抛出 AccessViolationException

asp.net - 用于远程可视化 ASP.NET 性能计数器的 Web 界面

c# - 将 CSS 类设置为选定的 ASP.NET Listview 项

c# - 进行内容协商时不使用 SupportedMediaTypes

c# - 是否可以在 C# 中向现有模块添加类型?

c# - 获取当月的星期一到星期六

asp.net-mvc - 每次验证后是否可以更改 ASP.NET MVC 中的 AntiForgeryToken 值?

c# - 接口(interface)和约束

asp.net-mvc - 在 ASP.net MVC 中通过 jQuery 在客户端本地化验证消息

c# - 用于 IEnumerable ViewModel 的 Razor Html.DisplayNameForInnerType