How can I read lines from a text file letter by letter? [closed]
I have an ASCII text file. I want to read the file, line by line, divide it by positions, and save every value to a database, using C#. How might I achieve this?
System.IO.File.ReadAllLines("file")
is the easiest way to get an array with each line of the file, but will load the whole thing into memory so might not be good for big files.
so something like
foreach (var line in File.ReadAllLines("file.txt")) {
var phoneNumber = line.Substring(0, 10); //get first 10 chars
var zipCode = line.Substring(10, 5); //get next 5 chars
... etc
... store to DB.
}
or alternatively in LINQ syntax, you could do
var data = from line in File.ReadAllLines(filename)
select new {Phone=line.Substring(0,10), Zip=line.Substring(10,5), ...};
foreach(var record in data) {
.. store to DB
}
Use StreamReader:
using (var input = new StreamReader(File.OpenRead(inputFileName), Encoding.ASCII))
{
string line;
while((line = input.ReadLine()) != null) // or read data other way you want
{
//Do something here...
}
}
I'm guessing you need something like this?
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
for(int i = 0; i < line.Length; i++){
//do something with line[i]
}
}
}
精彩评论