首页 > 解决方案 > 从文件中读取一行后如何获取当前文件位置?

问题描述

在 C# 中如何读取一行以及读取后如何获取文件当前位置?

FileStream fStream = File.OpenRead(filePath);
 var reader = new StreamReader(fStream);
 while (!reader.EndOfStream)
 {

 string line = reader.ReadLine();

 }

如果我调用 fStream.Position ,则在读取一行后,它将位置值仅作为整个文件长度。

标签: c#

解决方案


IMO 您使用的文件太小,并希望在仅阅读一行后,阅读器会继续前进。那是错误的假设。BaseStream.Position 获取或设置当前流中的位置。

看,下图,微软开发人员写的。

在此处输入图像描述

当然,我们可以创建一个例子。让我们考虑以下代码段。

using System;
using System.IO;

namespace ConsoleApp26
{
    class Program
    {
        static void Main(string[] args)
        {
            var fStream = File.OpenRead(@"C:\TEMP\test.xml");
            var reader = new StreamReader(fStream);
            var i = 0;
            while (!reader.EndOfStream)
            {

                var line = reader.ReadLine();
                i++;
                Console.WriteLine(
                    $"Line number {i}.Line contents {line}. Reader position is {reader.BaseStream.Position}/{reader.BaseStream.Length}");

            }

            Console.ReadLine();
        }
    }
}

该文件的内容写在下面。因此,您可以轻松地在 PC 上创建相同的文件。

<?xml version="1.0"?>

-<xml>


-<cards>

<name>Majespecter Toad - Ogama</name>

<type>Pendulum Effect Monster</type>

<desc>When this card is Normal or Special Summoned: You can Set 1 "Majespecter" Spell/Trap Card directly from your Deck, but it cannot activate this turn. You can only use this effect of "Majespecter Toad - Ogama" once per turn. Cannot be targeted or destroyed </desc>

<race>Spellcaster</race>

<image_url>https://storage.googleapis.com/ygoprodeck.com/pics/645794.jpg</image_url>

<atk>1300</atk>

<def>500</def>

<level>4</level>

</cards>


-<cards>

<name>Gladiator Beast Retiari</name>

<type>Effect Monster</type>

<desc>When this card is Special Summoned by the effect of a "Gladiator Beast" monster, you can remove from play 1 card from your opponent's Graveyard. At the end of the Battle Phase, if this card attacked or was attacked, you can return it to the Deck to Specia</desc>

<race>Aqua</race>

<image_url>https://storage.googleapis.com/ygoprodeck.com/pics/612115.jpg</image_url>

<atk>1200</atk>

<def>800</def>

<level>3</level>

</cards>


-<cards>

<name>Malefic Rainbow Dragon</name>

<type>Effect Monster</type>

<desc>This card cannot be Normal Summoned or Set. This card cannot be Special Summoned, except by removing from play 1 "Rainbow Dragon" from your hand or Deck. There can only be 1 face-up "Malefic" monster on the field. Other monsters you control cannot declare</desc>

<race>Dragon</race>

<image_url>https://storage.googleapis.com/ygoprodeck.com/pics/598988.jpg</image_url>

<atk>4000</atk>

<def>0</def>

<level>10</level>

</cards>

</xml>

以及输出的样子,请参见下图。虽然,我们正在读取行,但位置并没有改变,因为块的大小是 1024 字节。 在此处输入图像描述


推荐阅读