繁体   English   中英

如何将以HttpPostedFIle形式上传的XML文件转换为C#asp.net中的字符串?

[英]How can I convert a uploaded XML file that is in the form of a HttpPostedFIle to a string in C# asp.net?

如何将以HttpPostedFIle形式上传的XML文件转换为C#asp.net中的字符串? 我正在尝试创建一种功能,可以上传XML文件并将其存储在使用我的Web应用程序的客户端的数据库服务器上。 我需要将其转换为字符串,以便可以对XML文件进行字符串处理,并删除XML文件中与SQL Server不兼容的某些元素。

我已经尝试过这个和其他一些东西。 我不断收到错误

InputStream不在当前上下文中

和另一个错误。

string xmlString = System.IO.File.ReadAllText(fl.InputStream.ToString());

            string fName = fl.FileName;
            if (fName.IndexOf("\\") != -1) { fName = fName.Substring(fName.LastIndexOf("\\") + 1); }
            string fileDataLink = uniqueName + Path.GetExtension(fName);
            outputPath += fileDataLink;
            fl.SaveAs(outputPath);
            transactionTypeID = Convert.ToInt32(Request["textInput"]);
            integrationTypeDt = DAC.ExecuteDataSetText(db.ConnectionString, "SELECT [StoredProcName], [Configuration] FROM [dbo].[ITransactionType] WITH(NOLOCK) WHERE [TransactionTypeID] =" + transactionTypeID, new string[] { "IntegrationType" }).Tables[0];

            string workbookXML = "";
            //load the file,
            string xmlString = System.IO.File.ReadAllText(fl.InputStream.ToString());

            //make changes

            //Assign the file to the XML var, 


            //and then save it into the database

我希望它返回上载的整个文件的字符串值。 相反,我遇到两个错误。 有人说InputStream不在当前上下文中。

有几种方法可以修复您的代码。 这将是一种方式:

        string fileDataLink = uniqueName + Path.GetExtension(fl.FileName);
        outputPath += fileDataLink;
        // not needed if you do not want the file on both disk and database 
        //fl.SaveAs(outputPath);

        transactionTypeID = Convert.ToInt32(Request["textInput"]);
        integrationTypeDt = DAC.ExecuteDataSetText(db.ConnectionString, "SELECT [StoredProcName], [Configuration] FROM [dbo].[ITransactionType] WITH(NOLOCK) WHERE [TransactionTypeID] =" + transactionTypeID, new string[] { "IntegrationType" }).Tables[0];

        string workbookXML = "";
        //load the file,
        string xmlString = null;
        using(var reader = new StreamReader(fl.InputStream))
        {
           xmlString = reader.ReadToEnd();
        }

另一种方法是保留SaveAs并编写:

string xmlString = System.IO.File.ReadAllText(outputPath);

这将从磁盘加载文件。

请注意两件事:

  1. 您的解决方案将整个xml文件加载到内存中进行处理。 在您的方案中,这可能不是问题,但是例如,如果您有许多用户,并且他们同时上传多个大文件,则服务器可能会用尽内存。 在这种情况下,最好尝试以某种方式将流作为流提供给数据库的其他解决方案。
  2. 绝对不能像在语句"SELECT [StoredProcName], [Configuration] FROM [dbo].[ITransactionType] WITH(NOLOCK) WHERE [TransactionTypeID] =" + transactionTypeID那样,将从网页输入的值连接起来"SELECT [StoredProcName], [Configuration] FROM [dbo].[ITransactionType] WITH(NOLOCK) WHERE [TransactionTypeID] =" + transactionTypeID改用SQL参数

暂无
暂无

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

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