【发布时间】: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