循环通过FileUpload控件上传的文本文件行
本文关键字:文本 文件 FileUpload 控件 循环 | 更新日期: 2023-09-27 18:06:32
我想选择一个简单的.txt文件,其中包含使用FileUpload控件的字符串行。但是,我想循环遍历每一行文本,并在ListBox控件中显示每一行,而不是实际保存文件。
文本文件示例:
用法
123 jhg345
182 bdh774
473 ypo433
129 iiu454
实现这一目标的最佳方法是什么?
目前为止我有什么:
private void populateListBox()
{
FileUpload fu = FileUpload1;
if (fu.HasFile)
{
//Loop trough txt file and add lines to ListBox1
}
}
private void populateListBox()
{
FileUpload fu = FileUpload1;
if (fu.HasFile)
{
StreamReader reader = new StreamReader(fu.FileContent);
do
{
string textLine = reader.ReadLine();
// do your coding
//Loop trough txt file and add lines to ListBox1
} while (reader.Peek() != -1);
reader.Close();
}
}
下面是一个工作示例:
using (var file = new System.IO.StreamReader("c:''test.txt"))
{
string line;
while ((line = file.ReadLine()) != null)
{
// do something awesome
}
}
将文件打开到StreamReader中并使用
while(!reader.EndOfStream)
{
reader.ReadLine;
// do your stuff
}
如果你想知道如何将文件/日期转换成流,请说明以何种形式获取文件(s字节)
有几种不同的方法可以做到这一点,上面的就是很好的例子。
string line;
string filePath = "c:''test.txt";
if (File.Exists(filePath))
{
// Read the file and display it line by line.
StreamReader file = new StreamReader(filePath);
while ((line = file.ReadLine()) != null)
{
listBox1.Add(line);
}
file.Close();
}
private void populateListBox()
{
List<string> tempListRecords = new List<string>();
if (!FileUpload1.HasFile)
{
return;
}
using (StreamReader tempReader = new StreamReader(FileUpload1.FileContent))
{
string tempLine = string.Empty;
while ((tempLine = tempReader.ReadLine()) != null)
{
// GET - line
tempListRecords.Add(tempLine);
// or do your coding....
}
}
}
还有这个,使用httppostdfilebase在MVC:
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
//var fileName = Path.GetFileName(file.FileName);
//var path = Path.Combine(directory.ToString(), fileName);
//file.SaveAs(path);
var streamfile = new StreamReader(file.InputStream);
var streamline = string.Empty;
var counter = 1;
var createddate = DateTime.Now;
try
{
while ((streamline = streamfile.ReadLine()) != null)
{
//do whatever;//