【问题标题】:File Upload read to memory and use as text file - is there a better way?文件上传读取到内存并用作文本文件 - 有没有更好的方法?
【发布时间】:2009-11-25 15:12:23
【问题描述】:

我有一个 Intranet 托管的 Web 应用程序,用户将在其中上传一个文本文件,其中包含 5 列中以空格分隔的数据。我不想保存文件,所以我只想在内存中使用它。我在网上尝试了许多不同的示例,但都没有奏效。最后一位同事向我展示了如何做到这一点。这是代码,我想知道是否有更好的方法来做到这一点。最后,我想要的只是一种将数据链接到网格视图或中继器以供查看和稍后存储到数据库(SQL Server)中的方法。

上传文件asp标签ID为SurveyFileUpload
SurveyDate 是一个 asp:input 字段

Int32 fileLen = SurveyFileUpload.PostedFile.ContentLength;

// Create a byte array to hold the contents of the file.
Byte[] buffer = new Byte[fileLen];

// Initialize the stream to read the uploaded file.
Stream s = SurveyFileUpload.FileContent;

// Read the file into the byte array.
s.Read(buffer, 0, fileLen);

// Convert byte array into characters.
ASCIIEncoding enc = new ASCIIEncoding();
string str = enc.GetString(buffer);
testReadFile(str, db_surveyDate.Text);

protected void testReadFile(string inFileString, string inSurveyDate)
{
    string[] lines = inFileString.Split('\n');
    curFileListing.InnerHtml = "";
    int curRow = 1;
    var readings = from line in lines
       select new
       {
           // this is just for display purposes to show the number of rows on the page
           Row = curRow++,
           SurveyDate = inSurveyDate,
           ItemNumber = Regex.Split(line, "[ ]+")[0],
           Northing = Regex.Split(line, "[ ]+")[1],
           Easting = Regex.Split(line, "[ ]+")[2],
           Elevation = Regex.Split(line, "[ ]+")[3],
           Name = Regex.Split(line, "[ ]+")[4]
       };
    saveFileData.Visible = true;
    GridView fileData = new GridView();
    fileData.DataSource = readings;
    fileData.DataBind();
    fileData.AlternatingRowStyle.BackColor = 
           System.Drawing.ColorTranslator.FromHtml("#eee");
    curFileListing.Controls.Add(fileData);
}

这工作正常。我对 LINQ 不是很了解,而且我在文件流部分遇到了困难。

【问题讨论】:

    标签: c# asp.net linq file-upload streaming


    【解决方案1】:

    我使用这种方法。我正在从一个文本文件中读取 ID 号,每行一个 ID 号:

    if (fileUpload.HasFile)
    {
        using (Stream fileStream = fileUpload.PostedFile.InputStream)
        using (StreamReader sr = new StreamReader(fileStream))
        {
            string idNum = null;
            while ((idNum = sr.ReadLine()) != null)
            {
                // Verify the line is in the expected id format
                if (Regex.IsMatch(idNum, this.InputRegex))
                {
                    // Do Stuff with input
                }
                else
                {
                    Log.LogDebug("{0}Invalid input format.", LoggingSettings.logPrefix);
                }
            }
        }
    
    }
    else
    {
        Log.LogDebug("{0}No file present.", LoggingSettings.logPrefix);
    }
    

    【讨论】:

      【解决方案2】:

      好吧,您可以只运行一次 Regex.Split(line, "[ ]+") 并使用存储的结果来填充字段。相比之下,正则表达式相当昂贵。

      另外,您是否检查过您的字段中是否有剩余的“\r”?许多文本文件同时包含“\n”和“\r”。

      【讨论】:

        【解决方案3】:

        除了MandoMando的建议外,没有太多。我假设它是原型代码(基于方法的名称)或者我会说文件处理的东西应该包装在一个类中以封装格式,并隔离对它的更改。

        实施删除 \r 的建议很简单。

        string[] lines = inFileString.Replace( '\r', '\n' ).Split( new[]{'\n'}, StringSplitOptions.RemoveEmptyEntries );
        

        为了清理对正则表达式函数的额外调用,您可以这样做。我没有 2008/10 工作来测试这些,但它们应该可以工作。

        var records = from line in lines
        select line.Split( ' ', StringSplitOptions.RemoveEmptyEntries );
        
        var readings = from record in records
                       select new 
                       {
                           Row = curRow++,
                           SurveyDate = inSurveyDate,
                           ItemNumber = record[0],
                           Northing = record[1],
                           Easting = record[2],
                           Elevation = record[3],
                           Name = record[4]
                       };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-25
          • 1970-01-01
          • 2012-10-22
          • 1970-01-01
          • 2021-06-30
          • 2012-06-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多