c# - 从文件中读取一行后如何获取当前文件位置?
问题描述
在 C# 中如何读取一行以及读取后如何获取文件当前位置?
FileStream fStream = File.OpenRead(filePath);
var reader = new StreamReader(fStream);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
}
如果我调用 fStream.Position ,则在读取一行后,它将位置值仅作为整个文件长度。
解决方案
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>
推荐阅读
- javascript - 如何在不点击的情况下调用点击事件?
- ios - Xcode Swift,控制台日志会影响 App Store 审批吗?无论如何,应用程序都可以正常工作
- java - 无法将用户的输入传递给数组
- c - 删除没有头指针的节点
- flutter - 如何使用 string.replace() 来实现所需的输出?
- c# - 在 NEST 中创建 IndexName 的实例
- multithreading - 将 emscripten webassembly 线程 (C++) 与 webpack (create-react-app) 一起使用
- javascript - 在 JavaScript 中提交时重置星值
- javascript - 无法在地图内添加检查以过滤掉详细信息
- amazon-web-services - 在 AWS 应用程序负载均衡器侦听器中添加路径