文件上传读取到内存并用作文本文件 - 有更好的方法吗?

Pol*_*era 2 c# linq asp.net streaming file-upload

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

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

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);
}
Run Code Online (Sandbox Code Playgroud)

这很好用.我对LINQ知之甚少,我对文件流部分很难.

m4t*_*mus 5

我用这种方法.我正在读取一个文本文件中的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);
}
Run Code Online (Sandbox Code Playgroud)