Question

Can someone help me in my problem? Because I'm having a hard time of on how to get the last input ID in a text file. My back end is a text file. Thanks.

this is the sample content of the text file of my program.

ID|CODE1|CODE2|EXPLAIN|CODE3|DATE|PRICE1|PRICE2|PRICE3| 02|JKDHG|hkjd|Hfdkhgfdkjgh|264|56.46.54|654 654.87|878 643.51|567 468.46| 03|DEJSL|hdsk|Djfglkdfjhdlf|616|46.54.56|654 654.65|465 465.46|546 546.54| 01|JANE|jane|Jane|251|56.46.54|534 654.65|654 642.54|543 468.74|

how would I get the last input id so that the id of the input line wouldn't back to number 1?

Was it helpful?

Solution

Make a function that read file and return list of lines(string) like this:

 public static List<string> ReadTextFileReturnListOfLines(string strPath)
{
    List<string> MyLineList = new List<string>();
    try
    {
        // Create an instance of StreamReader to read from a file.
        StreamReader sr = new StreamReader(strPath);
        string line = null;
        // Read and display the lines from the file until the end 
        // of the file is reached.
        do
        {
            line = sr.ReadLine();
            if (line != null)
            {
                MyLineList.Add(line);
            }
        } while (!(line == null));
        sr.Close();
        return MyLineList;
    }
    catch (Exception E)
    {
        throw E;
    }
}

I am not sure if ID|CODE1|CODE2|EXPLAIN|CODE3|DATE|PRICE1|PRICE2|PRICE3| is part of the file but you have to adjust the index of the element you want to get , then get the element in the list.

MyStringList(1).split("|")(0);

OTHER TIPS

If you're looking for the last (highest) number in the ID field, you could do it with a single line in LINQ:

Dim MaxID = (From line in File.ReadAllLines("file.txt")
             Skip 1
             Select line.Split("|")(0)).Max()

What this code does is gets an array via File.ReadAllLines, skips the first line (which appears to be a header), splits each line on the delimiter (|), takes the first element from that split (which is ID) and selects the maximum value.

In the case of your sample input, the result is "03".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top