我有一个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知之甚少,而且我对文件流部分很难。
答案 0 :(得分: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);
}
答案 1 :(得分:1)
好吧,你只能运行Regex.Split(line,“[] +”)一次并使用存储的结果来填充字段。相比之下,正则表达式相当昂贵。
此外,您是否检查过字段中是否遗留了'\ r'?许多文本文件都包含'\ n'和'\ r'。
答案 2 :(得分:1)
除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]
};