要限制.NET中StreamReader.ReadLine()读取的字符数,可以使用以下方法:
using (var reader = new StreamReader("file.txt"))
{
char[] buffer = new char[10]; // 设置缓冲区大小
int charsRead = 0;
while ((charsRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
// 处理读取到的字符数组
string result = new string(buffer, 0, charsRead);
}
}
using (var reader = new StreamReader("file.txt"))
{
char[] buffer = new char[10]; // 设置缓冲区大小
int charsRead = 0;
while ((charsRead = reader.ReadBlock(buffer, 0, buffer.Length)) > 0)
{
// 处理读取到的字符数组
string result = new string(buffer, 0, charsRead);
}
}
using (var reader = new StreamReader("file.txt"))
{
string line;
StringBuilder sb = new StringBuilder();
int totalCharsRead = 0;
while ((line = reader.ReadLine()) != null)
{
int charsToRead = Math.Min(10 - totalCharsRead, line.Length); // 设置每次读取的字符数
sb.Append(line.Substring(0, charsToRead));
totalCharsRead += charsToRead;
if (totalCharsRead == 10) // 达到指定字符数,进行处理
{
// 处理读取到的字符串
string result = sb.ToString();
sb.Clear();
totalCharsRead = 0;
}
}
}
这些方法可以帮助您限制StreamReader.ReadLine()读取的字符数。
领取专属 10元无门槛券
手把手带您无忧上云