StreamReader.Peek 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
返回下一个可用字符,但不使用该字符。
public:
override int Peek();
public override int Peek();
override this.Peek : unit -> int
Public Overrides Function Peek () As Integer
返回
一个整数,表示要读取的下一个字符,或者 -1 如果没有要读取的字符,或者流不支持查找。
例外
出现 I/O 错误。
示例
下面的代码示例从文件读取行,直到到达文件末尾。
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
try
{
if (File.Exists(path))
{
File.Delete(path);
}
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("This");
sw.WriteLine("is some text");
sw.WriteLine("to test");
sw.WriteLine("Reading");
}
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() > -1)
{
Console.WriteLine(sr.ReadLine());
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Try
If File.Exists(path) Then
File.Delete(path)
End If
Dim sw As StreamWriter = New StreamWriter(path)
sw.WriteLine("This")
sw.WriteLine("is some text")
sw.WriteLine("to test")
sw.WriteLine("Reading")
sw.Close()
Dim sr As StreamReader = New StreamReader(path)
Do While sr.Peek() > -1
Console.WriteLine(sr.ReadLine())
Loop
sr.Close()
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
注解
该方法 Peek 返回一个整数值,以确定文件末尾还是发生了另一个错误。 这样,用户就可以先检查返回的值是否 -1,然后再将其 Char 转换为类型。
此方法重写 TextReader.Peek。
对象的StreamReader当前位置不会更改。Peek