简体   繁体   English

c# 读取文本文件,但只需将特定行保存在数组中

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

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我有一个文本文件,其中包含一些数据,格式如下:ID、Box1、Box2、Box3、Box4、Box5、Box6、Box7、Box8、Box9、Box10、Box11、Box12、Box13、Box14

The Id is always 7 digits long. ID 始终为 7 位数字。 and in the other fields will stand a time or can also be null.而在其他领域会立时也可以是null。 Now i have to check if an ID is already existing.现在我必须检查一个 ID 是否已经存在。 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.如果 Id 存在,我想将此行保存在一个由“,”分隔的数组中,然后更改时间或添加一个。 And after this array should be rewritten in the textfile.并且在这个数组之后应该在文本文件中重写。

How to do it??怎么做??

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;有点不清楚您在寻找什么,但听起来您有一个文件,其中每一行都以 ID 开头,后跟以逗号分隔的值列表; and the goal is to see if a specific ID exists, and if it does, save the values associated with it to an array.目标是查看特定 ID 是否存在,如果存在,则将与其关联的值保存到数组中。

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.一种方法是逐行读取文件,对于每一行,将其拆分为,分隔符,并将第一项(在索引0处)与我们正在搜索的 ID 进行比较。 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;                
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM