从文件读取一行后如何获取当前文件位置?

时间:2019-05-16 14:54:30

标签: c#

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

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

 string line = reader.ReadLine();

 }

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

1 个答案:

答案 0 :(得分:0)

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

请参见下图,Microsoft开发人员编写的内容。

enter image description here

当然,我们可以创建一个示例。让我们考虑以下片段。

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字节。 enter image description here