开发者

How can I read lines from a text file letter by letter? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarify开发者_如何转开发ing this question so that it can be reopened, visit the help center. Closed 11 years ago.

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]  
                }

        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜