File Upload read to memory and use as text file - is there a better way?
I have a intranet hosted web application where the user will upload a text file with space delimited data in 5 columns. I don't wish to save the file so I wanted to just use it in memory. I tried many different examples off the web and none worked. Finally a co-worker showed me how to do this. Here is the code and I'm wondering if there is a better way to do this. In the end, all I want is a way to link the data to a gridview or repeater for viewing and later storage into a database (SQL Server).
The upload file asp tag ID is SurveyFileUpload
The SurveyDate is an asp:input fieldInt32 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.AlternatingRowSty开发者_运维百科le.BackColor =
System.Drawing.ColorTranslator.FromHtml("#eee");
curFileListing.Controls.Add(fileData);
}
This works OK. I'm not that knowledgeable with LINQ and I had a hard time with the file stream part.
I use this method. I am reading in id numbers from a text file with one id number per line:
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);
}
Well, you could run Regex.Split(line, "[ ]+") only once and use the stored result to populate the fields. Regex is fairly expensive by comparison.
Also, have you checked to see if there are left over '\r' in your fields? Many text files contain both '\n' and '\r'.
Other than the suggestions from MandoMando, there isn't much. I'm assuming it is prototype code (based on the name of the method) or I would say the file handling stuff should be wrapped in a class to encapsulate the format, and isolate changes to it.
Implementing the suggestion of removing the \r is simple enough.
string[] lines = inFileString.Replace( '\r', '\n' ).Split( new[]{'\n'}, StringSplitOptions.RemoveEmptyEntries );
For cleaning up the extra calls to the regex functions, you could do it like so. I don't have 2008/10 at work to test these, but they should work.
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]
};
精彩评论