0

如何将上传的 HttpPostedFIle 形式的 XML 文件转换为 C# asp.net 中的字符串?我正在尝试为使用我的 Web 应用程序的客户端创建上传 XML 文件并将其存储在数据库服务器上的功能。我需要将其转换为字符串,以便对 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 不在当前上下文中。

4

1 回答 1

1

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

        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. 永远不应该将一个从网页输入的值连接到你的 sql 中,就像在语句 "SELECT [StoredProcName], [Configuration] FROM [dbo].[ITransactionType] WITH(NOLOCK) WHERE [TransactionTypeID] =" + transactionTypeID使用SQL 参数中所做的那样。
于 2019-04-03T08:37:01.560 回答