I want to select a simple .txt file that contains lines of strings using a FileUpload control. But instead of actually saving the file I want to loop through each line of text and display each line in a ListBox control.
Example of a text file:
test.txt
123jhg345
182bdh774
473ypo433
129iiu454
What is the best way to accomplish this?
What I have so far:
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();
}
}
Here's a working example:
using (var file = new System.IO.StreamReader("c:\\test.txt"))
{
string line;
while ((line = file.ReadLine()) != null)
{
// do something awesome
}
}
open the file into a StreamReader and use
while(!reader.EndOfStream)
{
reader.ReadLine;
// do your stuff
}
If you want to know how to get the file/date into a stream please say in what form you get the file(s bytes)
There are a few different ways of doing this, the ones above are good examples.
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();
}
There is this as well, using HttpPostedFileBase in 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;//
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....
}
}
}