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

我有一个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); } 

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

我用这种方法。 我正在读取一个文本文件中的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); } 

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

另外,你有没有检查过你的字段中是否还剩下’\ r’? 许多文本文件都包含’\ n’和’\ r’。

除了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] };