StreamReader.Read Methode
Definition
Liest das nächste Zeichen oder die nächste Gruppe von Zeichen aus dem Eingabestream.Reads the next character or next set of characters from the input stream.
Überlädt
Read() |
Liest das nächste Zeichen aus dem Eingabestream und verschiebt die Zeichenposition um ein Zeichen nach vorn.Reads the next character from the input stream and advances the character position by one character. |
Read(Span<Char>) |
Liest die Zeichen aus dem aktuellen Datenstrom in eine Spanne.Reads the characters from the current stream into a span. |
Read(Char[], Int32, Int32) |
Liest vom aktuellen Stream ein angegebenes Maximum von Zeichen in einen Puffer ein und beginnt dabei am angegebenen Index.Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index. |
Read()
Liest das nächste Zeichen aus dem Eingabestream und verschiebt die Zeichenposition um ein Zeichen nach vorn.Reads the next character from the input stream and advances the character position by one character.
public:
override int Read();
public override int Read ();
override this.Read : unit -> int
Public Overrides Function Read () As Integer
Gibt zurück
Das nächste Zeichen im Eingabestream wird als Int32-Objekt dargestellt, oder -1, wenn keine weiteren Zeichen verfügbar sind.The next character from the input stream represented as an Int32 object, or -1 if no more characters are available.
Ausnahmen
Ein E/A-Fehler tritt auf.An I/O error occurs.
Beispiele
Im folgenden Codebeispiel wird eine einfache Verwendung der- Read Methode veranschaulicht.The following code example demonstrates a simple use of the Read method.
using namespace System;
using namespace System::IO;
int main()
{
String^ path = "c:\\temp\\MyTest.txt";
try
{
if ( File::Exists( path ) )
{
File::Delete( path );
}
StreamWriter^ sw = gcnew StreamWriter( path );
try
{
sw->WriteLine( "This" );
sw->WriteLine( "is some text" );
sw->WriteLine( "to test" );
sw->WriteLine( "Reading" );
}
finally
{
delete sw;
}
StreamReader^ sr = gcnew StreamReader( path );
try
{
while ( sr->Peek() >= 0 )
{
Console::Write( (Char)sr->Read() );
}
}
finally
{
delete sr;
}
}
catch ( Exception^ e )
{
Console::WriteLine( "The process failed: {0}", e );
}
}
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() >= 0)
{
Console.Write((char)sr.Read());
}
}
}
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() >= 0
Console.Write(Convert.ToChar(sr.Read()))
Loop
sr.Close()
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
Das folgende Codebeispiel veranschaulicht das Lesen eines einzelnen Zeichens mithilfe der- Read() Methoden Überladung, wobei die Ausgabe der ASCII-Ganzzahl als Dezimal-und hexadezimal formatiertThe following code example demonstrates reading a single character using the Read() method overload, formatting the ASCII integer output as decimal and hexadecimal.
using namespace System;
using namespace System::IO;
int main()
{
//Create a FileInfo instance representing an existing text file.
FileInfo^ MyFile = gcnew FileInfo( "c:\\csc.txt" );
//Instantiate a StreamReader to read from the text file.
StreamReader^ sr = MyFile->OpenText();
//Read a single character.
int FirstChar = sr->Read();
//Display the ASCII number of the character read in both decimal and hexadecimal format.
Console::WriteLine( "The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar );
//
sr->Close();
}
using System;
using System.IO;
class StrmRdrRead
{
public static void Main()
{
//Create a FileInfo instance representing an existing text file.
FileInfo MyFile=new FileInfo(@"c:\csc.txt");
//Instantiate a StreamReader to read from the text file.
StreamReader sr=MyFile.OpenText();
//Read a single character.
int FirstChar=sr.Read();
//Display the ASCII number of the character read in both decimal and hexadecimal format.
Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.",
FirstChar, FirstChar);
//
sr.Close();
}
}
Imports System.IO
Class StrmRdrRead
Public Shared Sub Main()
'Create a FileInfo instance representing an existing text file.
Dim MyFile As New FileInfo("c:\csc.txt")
'Instantiate a StreamReader to read from the text file.
Dim sr As StreamReader = MyFile.OpenText()
'Read a single character.
Dim FirstChar As Integer = sr.Read()
'Display the ASCII number of the character read in both decimal and hexadecimal format.
Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.", FirstChar, FirstChar)
sr.Close()
End Sub
End Class
Hinweise
Diese Methode überschreibt TextReader.Read.This method overrides TextReader.Read.
Diese Methode gibt eine ganze Zahl zurück, sodass Sie-1 zurückgeben kann, wenn das Ende des Streams erreicht wurde.This method returns an integer so that it can return -1 if the end of the stream has been reached. Wenn Sie die Position des zugrunde liegenden Streams nach dem Lesen von Daten in den Puffer ändern, entspricht die Position des zugrunde liegenden Streams möglicherweise nicht der Position des internen Puffers.If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. Um den internen Puffer zurückzusetzen, müssen Sie die- DiscardBufferedData Methode aufrufen. diese Methode verlangsamt jedoch die Leistung und sollte nur aufgerufen werden, wenn dies unbedingt erforderlich ist.To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.
Eine Liste der allgemeinen e/a-Aufgaben finden Sie unter Allgemeine e/a-Aufgaben.For a list of common I/O tasks, see Common I/O Tasks.
Siehe auch
- Datei- und Stream-E/AFile and Stream I/O
- Vorgehensweise: Lesen von Text aus einer DateiHow to: Read Text from a File
- Vorgehensweise: Schreiben von Text in eine DateiHow to: Write Text to a File
Gilt für:
Read(Span<Char>)
Liest die Zeichen aus dem aktuellen Datenstrom in eine Spanne.Reads the characters from the current stream into a span.
public:
override int Read(Span<char> buffer);
public override int Read (Span<char> buffer);
override this.Read : Span<char> -> int
Public Overrides Function Read (buffer As Span(Of Char)) As Integer
Parameter
Enthält nach dem Beenden dieser Methode die angegebene Zeichenspanne, die durch die aus der aktuellen Quelle gelesenen Zeichen ersetzt wurdeWhen this method returns, contains the specified span of characters replaced by the characters read from the current source.
Gibt zurück
Die Anzahl der gelesenen Zeichen, bzw. 0 (null), wenn das Ende des Streams erreicht ist und keine Daten gelesen wurden.The number of characters that have been read, or 0 if at the end of the stream and no data was read. Die Anzahl ist kleiner oder gleich der buffer
-Länge, abhängig davon, ob die Daten im Datenstrom verfügbar sind.The number will be less than or equal to the buffer
length, depending on whether the data is available within the stream.
Ausnahmen
Die Anzahl der aus dem Datenstrom gelesenen Zeichen ist größer als die buffer
-Länge.The number of characters read from the stream is larger than the buffer
length.
buffer
ist null
.buffer
is null
.
Gilt für:
Read(Char[], Int32, Int32)
Liest vom aktuellen Stream ein angegebenes Maximum von Zeichen in einen Puffer ein und beginnt dabei am angegebenen Index.Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index.
public:
override int Read(cli::array <char> ^ buffer, int index, int count);
public override int Read (char[] buffer, int index, int count);
override this.Read : char[] * int * int -> int
Public Overrides Function Read (buffer As Char(), index As Integer, count As Integer) As Integer
Parameter
- buffer
- Char[]
Wenn diese Methode zurückgegeben wird, enthält dieser Parameter das angegebene Zeichenarray mit den Werten zwischen index
und (index + count –1
), die durch die aus der aktuellen Quelle gelesenen Zeichen ersetzt wurden.When this method returns, contains the specified character array with the values between index
and (index + count - 1
) replaced by the characters read from the current source.
- index
- Int32
Der Index von buffer
, bei dem mit dem Schreiben begonnen wird.The index of buffer
at which to begin writing.
- count
- Int32
Die maximale Anzahl der zu lesenden Zeichen.The maximum number of characters to read.
Gibt zurück
Die Anzahl der gelesenen Zeichen, bzw. 0 (null), wenn das Ende des Streams erreicht ist und keine Daten gelesen wurden.The number of characters that have been read, or 0 if at the end of the stream and no data was read. Die Anzahl ist gleich dem count
-Parameter oder kleiner, abhängig davon, ob die Daten im Stream verfügbar sind.The number will be less than or equal to the count
parameter, depending on whether the data is available within the stream.
Ausnahmen
Die Pufferlänge minus index
ist kleiner als count
.The buffer length minus index
is less than count
.
buffer
ist null
.buffer
is null
.
index
oder count
ist ein negativer Wert.index
or count
is negative.
Ein E/A-Fehler tritt auf, der Stream wird z. B. geschlossen.An I/O error occurs, such as the stream is closed.
Beispiele
Im folgenden Codebeispiel werden fünf Zeichen gleichzeitig gelesen, bis das Ende der Datei erreicht ist.The following code example reads five characters at a time until the end of the file is reached.
using namespace System;
using namespace System::IO;
int main()
{
String^ path = "c:\\temp\\MyTest.txt";
try
{
if ( File::Exists( path ) )
{
File::Delete( path );
}
StreamWriter^ sw = gcnew StreamWriter( path );
try
{
sw->WriteLine( "This" );
sw->WriteLine( "is some text" );
sw->WriteLine( "to test" );
sw->WriteLine( "Reading" );
}
finally
{
delete sw;
}
StreamReader^ sr = gcnew StreamReader( path );
try
{
//This is an arbitrary size for this example.
array<Char>^c = nullptr;
while ( sr->Peek() >= 0 )
{
c = gcnew array<Char>(5);
sr->Read( c, 0, c->Length );
//The output will look odd, because
//only five characters are read at a time.
Console::WriteLine( c );
}
}
finally
{
delete sr;
}
}
catch ( Exception^ e )
{
Console::WriteLine( "The process failed: {0}", e );
}
}
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))
{
//This is an arbitrary size for this example.
char[] c = null;
while (sr.Peek() >= 0)
{
c = new char[5];
sr.Read(c, 0, c.Length);
//The output will look odd, because
//only five characters are read at a time.
Console.WriteLine(c);
}
}
}
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() >= 0
'This is an arbitrary size for this example.
Dim c(5) As Char
sr.Read(c, 0, c.Length)
'The output will look odd, because
'only five characters are read at a time.
Console.WriteLine(c)
Loop
sr.Close()
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
Hinweise
Diese Methode überschreibt TextReader.Read.This method overrides TextReader.Read.
Diese Methode gibt eine ganze Zahl zurück, sodass Sie 0 (null) zurückgeben kann, wenn das Ende des Streams erreicht ist.This method returns an integer so that it can return 0 if the end of the stream has been reached.
Wenn die- Read Methode verwendet wird, ist es effizienter, einen Puffer zu verwenden, der dieselbe Größe wie der interne Puffer des Streams hat, wobei der interne Puffer auf die gewünschte Blockgröße festgelegt ist und immer kleiner als die Blockgröße ist.When using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. Wenn die Größe des internen Puffers nicht angegeben wurde, als der Stream erstellt wurde, beträgt die Standardgröße 4 Kilobyte (4096 Bytes).If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes). Wenn Sie die Position des zugrunde liegenden Streams nach dem Lesen von Daten in den Puffer ändern, entspricht die Position des zugrunde liegenden Streams möglicherweise nicht der Position des internen Puffers.If you manipulate the position of the underlying stream after reading data into the buffer, the position of the underlying stream might not match the position of the internal buffer. Um den internen Puffer zurückzusetzen, müssen Sie die- DiscardBufferedData Methode aufrufen. diese Methode verlangsamt jedoch die Leistung und sollte nur aufgerufen werden, wenn dies unbedingt erforderlich ist.To reset the internal buffer, call the DiscardBufferedData method; however, this method slows performance and should be called only when absolutely necessary.
Diese Methode gibt zurück, nachdem entweder die Anzahl der vom- count
Parameter angegebenen Zeichen gelesen oder das Ende der Datei erreicht wurde.This method returns after either the number of characters specified by the count
parameter are read, or the end of the file is reached. ReadBlock ist eine blockierende Version von Read .ReadBlock is a blocking version of Read.
Eine Liste der allgemeinen e/a-Aufgaben finden Sie unter Allgemeine e/a-Aufgaben.For a list of common I/O tasks, see Common I/O Tasks.
Siehe auch
- Datei- und Stream-E/AFile and Stream I/O
- Vorgehensweise: Lesen von Text aus einer DateiHow to: Read Text from a File
- Vorgehensweise: Schreiben von Text in eine DateiHow to: Write Text to a File