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).
I am using Visual Studio 2008, C#, .NET 3.5
The upload file asp tag ID is SurveyFileUpload
The SurveyDate is an asp:input field
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);
}
This works OK. I'm not that knowledgeable with LINQ and I had a hard time with the file stream part. Thanx for your time.