FileStream的共享文件指针导致读取冲突
多个streamreader同时读取同一个filestream会相互干扰,根本原因是它们共享底层的文件位置指针。当第一个流读取数据时,文件指针会向后移动,此时第二个流再尝试读取,就会从新的指针位置开始,从而读到错误的数据或丢失前面的内容。

using System;
using System.IO;
using System.Text;
namespace SharedStreamDemo
{
class Program
{
static void Main()
{
string path = "test.txt";
File.WriteAllText(path, "Hello World");
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
// 两个 StreamReader 共享同一个 FileStream
using (StreamReader sr1 = new StreamReader(fs))
using (StreamReader sr2 = new StreamReader(fs))
{
Console.WriteLine("sr1 reads: " + sr1.ReadLine());
Console.WriteLine("sr2 reads: " + sr2.ReadLine());
}
}
}
}
}
运行上述代码,控制台输出如下:
sr1 reads: Hello World sr2 reads:
可以看到,sr1成功读取了整行文本,而sr2读到了空字符串。这是因为sr1在读取过程中推进了FileStream的内部指针,导致sr2从文件末尾开始读取,自然无法获取有效数据。
使用独立FileStream实例避免干扰
要避免这种干扰,最稳妥的方法是为每个StreamReader创建独立的FileStream实例。这样每个流都有自己独立的文件指针,互不影响。

using System;
using System.IO;
namespace IndependentStreamsDemo
{
class Program
{
static void Main()
{
string path = "test.txt";
File.WriteAllText(path, "Hello World");
// 为每个 StreamReader 创建独立的 FileStream
using (FileStream fs1 = new FileStream(path, FileMode.Open, FileAccess.Read))
using (StreamReader sr1 = new StreamReader(fs1))
using (FileStream fs2 = new FileStream(path, FileMode.Open, FileAccess.Read))
using (StreamReader sr2 = new StreamReader(fs2))
{
Console.WriteLine("sr1 reads: " + sr1.ReadLine());
Console.WriteLine("sr2 reads: " + sr2.ReadLine());
}
}
}
}
再次运行代码,这次两个StreamReader都能正确读取到“Hello World”:
sr1 reads: Hello World sr2 reads: Hello World
这是因为每个FileStream都从文件的起始位置开始读取,彼此之间没有共享状态,因此不会发生指针冲突。
基于FileStream.Position的具体问题
在实际开发中,如果必须共享同一个FileStream,可以通过手动管理Position属性来协调读取行为。例如,在每次读取前重置指针到指定位置,可以确保数据一致性。
using System;
using System.IO;
namespace PositionControlDemo
{
class Program
{
static void Main()
{
string path = "test.txt";
File.WriteAllText(path, "Hello World");
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (StreamReader sr1 = new StreamReader(fs))
using (StreamReader sr2 = new StreamReader(fs))
{
// 手动控制位置
fs.Position = 0;
Console.WriteLine("sr1 reads: " + sr1.ReadLine());
fs.Position = 0; // 重置指针
Console.WriteLine("sr2 reads: " + sr2.ReadLine());
}
}
}
}
通过这种方式,即使共享同一个FileStream,也能保证每个StreamReader从正确的起始位置读取数据,避免了因指针偏移导致的读取错误。










