Is there an option “go to line” in TextReader/StreamReader?

前端 未结 5 740
夕颜
夕颜 2021-01-18 01:16

I have a huge text file with 25k lines.Inside that text file each line starts with \"1 \\t (linenumber)\"

Example:

1   1   ITEM_ETC_GOLD_01    골드(소)          


        
5条回答
  •  臣服心动
    2021-01-18 01:59

    You can't jump directly to a line in a text file unless every line is fixed width and you are using a fixed-width encoding (i.e. not UTF-8 - which is one of the most common now).

    The only way to do it is to read lines and discard the ones you don't want.

    Alternatively, you might put an index at the top of the file (or in an external file) that tells it (for example) that line 1000 starts at byte offset [x], line 2000 starts at byte offset [y] etc. Then use .Position or .Seek() on the FileStream to move to the nearest indexed point, and walk forwards.

    Assuming the simplest approach (no index), the code in Jon's example should work fine. If you don't want LINQ, you can knock up something similar in .NET 2.0 + C# 2.0:

    // to read multiple lines in a block
    public static IEnumerable ReadLines(
            string path, int lineIndex, int count) {
        if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
        if (lineIndex < 0) throw new ArgumentOutOfRangeException("lineIndex");
        if (count < 0) throw new ArgumentOutOfRangeException("count");
        using (StreamReader reader = File.OpenText(path)) {
            string line;
            while (count > 0 && (line = reader.ReadLine()) != null) {
                if (lineIndex > 0) {
                    lineIndex--; // skip
                    continue;
                }
                count--;
                yield return line;
            }
        }
    }
    // to read a single line
    public static string ReadLine(string path, int lineIndex) {
        foreach (string line in ReadLines(path, lineIndex, 1)) {
            return line;
        }
        throw new IndexOutOfRangeException();
    }
    

    If you need to test values of the line (rather than just line index), then that is easy enough to do too; just tweak the iterator block.

提交回复
热议问题