StreamReader.Read Metoda
Definicja
Ważne
Niektóre informacje odnoszą się do produktu w wersji wstępnej, który może zostać znacząco zmodyfikowany przed wydaniem. Firma Microsoft nie udziela żadnych gwarancji, jawnych lub domniemanych, w odniesieniu do informacji podanych w tym miejscu.
Odczytuje następny znak lub następny zestaw znaków ze strumienia wejściowego.
Przeciążenia
Read() |
Odczytuje następny znak ze strumienia wejściowego i rozwija pozycję znaku o jeden znak. |
Read(Span<Char>) |
Odczytuje znaki z bieżącego strumienia do zakresu. |
Read(Char[], Int32, Int32) |
Odczytuje określoną maksymalną liczbę znaków z bieżącego strumienia do buforu, zaczynając od określonego indeksu. |
Read()
- Źródło:
- StreamReader.cs
- Źródło:
- StreamReader.cs
- Źródło:
- StreamReader.cs
Odczytuje następny znak ze strumienia wejściowego i rozwija pozycję znaku o jeden znak.
public:
override int Read();
public override int Read ();
override this.Read : unit -> int
Public Overrides Function Read () As Integer
Zwraca
Następny znak ze strumienia wejściowego Int32 reprezentowany jako obiekt lub -1, jeśli nie są dostępne żadne znaki.
Wyjątki
Wystąpi błąd We/Wy.
Przykłady
Poniższy przykład kodu przedstawia proste użycie Read metody.
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
Poniższy przykład kodu pokazuje odczytywanie pojedynczego znaku przy użyciu przeciążenia metody, formatowanie danych wyjściowych liczby całkowitej Read() ASCII jako dziesiętnych i szesnastkowe.
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
Uwagi
Ta metoda zastępuje TextReader.Read.
Ta metoda zwraca liczbę całkowitą, aby mogła zwrócić wartość -1, jeśli osiągnięto koniec strumienia. W przypadku manipulowania położeniem strumienia bazowego po odczytaniu danych do buforu pozycja bazowego strumienia może nie być zgodna z położeniem buforu wewnętrznego. Aby zresetować bufor wewnętrzny, wywołaj metodę DiscardBufferedData , jednak ta metoda spowalnia wydajność i powinna być wywoływana tylko wtedy, gdy jest to absolutnie konieczne.
Aby uzyskać listę typowych zadań we/wy, zobacz Typowe zadania we/wy.
Zobacz też
- We/wy pliku i strumienia
- Instrukcje: Odczytywanie tekstu z pliku
- Instrukcje: Zapisywanie tekstu w pliku
Dotyczy
Read(Span<Char>)
- Źródło:
- StreamReader.cs
- Źródło:
- StreamReader.cs
- Źródło:
- StreamReader.cs
Odczytuje znaki z bieżącego strumienia do zakresu.
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
Parametry
Gdy ta metoda zostanie zwrócona, zawiera określony zakres znaków zastąpiony przez znaki odczytywane z bieżącego źródła.
Zwraca
Liczba znaków, które zostały odczytane lub 0, jeśli na końcu strumienia nie zostały odczytane żadne dane. Liczba będzie mniejsza lub równa buffer
długości, w zależności od tego, czy dane są dostępne w strumieniu.
Wyjątki
Liczba znaków odczytywanych ze strumienia jest większa niż buffer
długość.
buffer
to null
.
Dotyczy
Read(Char[], Int32, Int32)
- Źródło:
- StreamReader.cs
- Źródło:
- StreamReader.cs
- Źródło:
- StreamReader.cs
Odczytuje określoną maksymalną liczbę znaków z bieżącego strumienia do buforu, zaczynając od określonego indeksu.
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
Parametry
- buffer
- Char[]
Gdy ta metoda zwraca, zawiera określoną tablicę znaków z wartościami między i (index + count - 1
) zastąpionymi znakami index
odczytanymi z bieżącego źródła.
- index
- Int32
Indeks, buffer
na którym należy rozpocząć pisanie.
- count
- Int32
Maksymalna liczba znaków do odczytania.
Zwraca
Liczba znaków, które zostały odczytane lub 0, jeśli na końcu strumienia nie zostały odczytane żadne dane. Liczba będzie mniejsza lub równa parametrowi count
, w zależności od tego, czy dane są dostępne w strumieniu.
Wyjątki
Długość buforu minus index
jest mniejsza niż count
.
buffer
to null
.
index
lub count
jest ujemny.
Występuje błąd we/wy, taki jak strumień jest zamknięty.
Przykłady
Poniższy przykład kodu odczytuje pięć znaków w czasie do momentu osiągnięcia końca pliku.
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
Uwagi
Ta metoda zastępuje TextReader.Read.
Ta metoda zwraca liczbę całkowitą, aby mogła zwrócić wartość 0, jeśli osiągnięto koniec strumienia.
W przypadku korzystania z Read metody jest bardziej wydajne użycie buforu, który jest taki sam jak wewnętrzny bufor strumienia, gdzie wewnętrzny bufor jest ustawiony na żądany rozmiar bloku i zawsze odczytywać mniej niż rozmiar bloku. Jeśli rozmiar buforu wewnętrznego nie został określona podczas konstruowania strumienia, jego domyślnym rozmiarem jest 4 kilobajty (4096 bajtów). W przypadku manipulowania położeniem strumienia bazowego po odczytaniu danych do buforu pozycja bazowego strumienia może nie być zgodna z położeniem buforu wewnętrznego. Aby zresetować bufor wewnętrzny, wywołaj metodę DiscardBufferedData , jednak ta metoda spowalnia wydajność i powinna być wywoływana tylko wtedy, gdy jest to absolutnie konieczne.
Ta metoda zwraca wartość po odczytaniu count
liczby znaków określonych przez parametr lub osiągnięto koniec pliku. ReadBlock jest zablokowaną wersją programu Read.
Aby uzyskać listę typowych zadań we/wy, zobacz Typowe zadania we/wy.
Zobacz też
- We/wy pliku i strumienia
- Instrukcje: Odczytywanie tekstu z pliku
- Instrukcje: Zapisywanie tekstu w pliku
Dotyczy
Opinia
https://aka.ms/ContentUserFeedback.
Dostępne już wkrótce: W 2024 r. będziemy stopniowo wycofywać zgłoszenia z serwisu GitHub jako mechanizm przesyłania opinii na temat zawartości i zastępować go nowym systemem opinii. Aby uzyskać więcej informacji, sprawdź:Prześlij i wyświetl opinię dla