c# read a text file, but just save a specific line in an array

Viewed 39

I have a textfile with some data in it with this style: ID, Box1, Box2, Box3, Box4, Box5, Box6, Box7, Box8, Box9, Box10, Box11, Box12, Box13, Box14

The Id is always 7 digits long. and in the other fields will stand a time or can also be null. Now i have to check if an ID is already existing. If the Id is existing i want to save this line int an array seperated by the",", to do then changes to the times or to add one. And after this array should be rewritten in the textfile.

How to do it??

1 Answers

It's a little unclear exactly what you're looking for, but it sounds like you have a file where every line starts with an ID, followed by a comma-separated list of values; and the goal is to see if a specific ID exists, and if it does, save the values associated with it to an array.

One way to do this is to read the file line by line, and for each line, split it on the , separator and compare the first item (at index 0) to the ID we're searching for. If it's a match, return the split values array.

public string[] GetLineWithID(string id, string filePath)
{
    if (id == null) throw new ArgumentNullException("id cannot be null.");
    if (filePath == null) throw new ArgumentNullException("filePath cannot be null.");
    if (!File.Exists(filePath)) throw new FileNotFoundException(filePath);
    
    foreach(var line in File.ReadLines(filePath))
    {
        var lineParts = line.Split(',');
        if (lineParts[0] == id) return lineParts; // Returns the CSV line as an array
    }
    
    return null;                
}
Related