Breyta

Deila með


Encoding.GetString Method

Definition

When overridden in a derived class, decodes a sequence of bytes into a string.

Overloads

GetString(Byte[])

When overridden in a derived class, decodes all the bytes in the specified byte array into a string.

GetString(ReadOnlySpan<Byte>)

When overridden in a derived class, decodes all the bytes in the specified byte span into a string.

GetString(Byte*, Int32)

When overridden in a derived class, decodes a specified number of bytes starting at a specified address into a string.

GetString(Byte[], Int32, Int32)

When overridden in a derived class, decodes a sequence of bytes from the specified byte array into a string.

GetString(Byte[])

Source:
Encoding.cs
Source:
Encoding.cs
Source:
Encoding.cs

When overridden in a derived class, decodes all the bytes in the specified byte array into a string.

public:
 virtual System::String ^ GetString(cli::array <System::Byte> ^ bytes);
public virtual string GetString (byte[] bytes);
abstract member GetString : byte[] -> string
override this.GetString : byte[] -> string
Public Overridable Function GetString (bytes As Byte()) As String

Parameters

bytes
Byte[]

The byte array containing the sequence of bytes to decode.

Returns

A string that contains the results of decoding the specified sequence of bytes.

Exceptions

The byte array contains invalid Unicode code points.

bytes is null.

A fallback occurred (for more information, see Character Encoding in .NET)

-and-

DecoderFallback is set to DecoderExceptionFallback.

Examples

The following example reads a UTF-8 encoded string from a binary file represented by a FileStream object. For files that are smaller than 2,048 bytes, it reads the contents of the entire file into a byte array and calls the GetString(Byte[]) method to perform the decoding. For larger files, it reads 2,048 bytes at a time into a byte array, calls the Decoder.GetCharCount(Byte[], Int32, Int32) method to determine how many characters are contained in the array, and then calls the Decoder.GetChars(Byte[], Int32, Int32, Char[], Int32) method to perform the decoding.

using System;
using System.IO;
using System.Text;

public class Example
{
   const int MAX_BUFFER_SIZE = 2048;
   static Encoding enc8 = Encoding.UTF8;

   public static void Main()
   {
      FileStream fStream = new FileStream(@".\Utf8Example.txt", FileMode.Open);
      string contents = null;
      
      // If file size is small, read in a single operation.
      if (fStream.Length <= MAX_BUFFER_SIZE) {
         Byte[] bytes = new Byte[fStream.Length];
         fStream.Read(bytes, 0, bytes.Length);
         contents = enc8.GetString(bytes);
      }
      // If file size exceeds buffer size, perform multiple reads.
      else {
         contents = ReadFromBuffer(fStream);
      }
      fStream.Close();
      Console.WriteLine(contents);
   }

   private static string ReadFromBuffer(FileStream fStream)
   {
        Byte[] bytes = new Byte[MAX_BUFFER_SIZE];
        string output = String.Empty;
        Decoder decoder8 = enc8.GetDecoder();
      
        while (fStream.Position < fStream.Length) {
           int nBytes = fStream.Read(bytes, 0, bytes.Length);
           int nChars = decoder8.GetCharCount(bytes, 0, nBytes);
           char[] chars = new char[nChars];
           nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0);
           output += new String(chars, 0, nChars);                                                     
        }
        return output;
    }
}
// The example displays the following output:
//     This is a UTF-8-encoded file that contains primarily Latin text, although it
//     does list the first twelve letters of the Russian (Cyrillic) alphabet:
//     
//     А б в г д е ё ж з и й к
//     
//     The goal is to save this file, then open and decode it as a binary stream.
Imports System.IO
Imports System.Text

Module Example
   Const MAX_BUFFER_SIZE As Integer = 2048
   
   Dim enc8 As Encoding = Encoding.UTF8
      
   Public Sub Main()
      Dim fStream As New FileStream(".\Utf8Example.txt", FileMode.Open)
      Dim contents As String = Nothing
      
      ' If file size is small, read in a single operation.
      If fStream.Length <= MAX_BUFFER_SIZE Then
         Dim bytes(CInt(fStream.Length) - 1) As Byte
         fStream.Read(bytes, 0, bytes.Length)
         contents = enc8.GetString(bytes)
      ' If file size exceeds buffer size, perform multiple reads.
      Else
         contents = ReadFromBuffer(fStream)
      End If
      fStream.Close()
      Console.WriteLine(contents)
   End Sub   

    Private Function ReadFromBuffer(fStream As FileStream) As String
        Dim bytes(MAX_BUFFER_SIZE) As Byte
        Dim output As String = String.Empty
        Dim decoder8 As Decoder = enc8.GetDecoder()
      
        Do While fStream.Position < fStream.Length
           Dim nBytes As Integer = fStream.Read(bytes, 0, bytes.Length)
           Dim nChars As Integer = decoder8.GetCharCount(bytes, 0, nBytes)
           Dim chars(nChars - 1) As Char
           nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0)
           output += New String(chars, 0, nChars)                                                     
        Loop
        Return output
    End Function
End Module
' The example displays the following output:
'     This is a UTF-8-encoded file that contains primarily Latin text, although it
'     does list the first twelve letters of the Russian (Cyrillic) alphabet:
'     
'     ? ? ? ? ? ? ? ? ? ? ? ?
'     
'     The goal is to save this file, then open and decode it as a binary stream.

The example uses the following text, which should be saved to a UTF-8 encoded file named Utf8Example.txt.

This is a UTF-8-encoded file that contains primarily Latin text, although it
does list the first twelve letters of the Russian (Cyrillic) alphabet:

А б в г д е ё ж з и й к

The goal is to save this file, then open and decode it as a binary stream.

Remarks

If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the Decoder object returned by the GetDecoder method of a derived class.

See the Remarks section of the Encoding.GetChars reference topic for a discussion of decoding techniques and considerations.

Note that the precise behavior of the GetString method for a particular Encoding implementation depends on the fallback strategy defined for that Encoding object. For more information, see the "Choosing a Fallback Strategy" section of the Character Encoding in .NET topic.

See also

Applies to

GetString(ReadOnlySpan<Byte>)

Source:
Encoding.cs
Source:
Encoding.cs
Source:
Encoding.cs

When overridden in a derived class, decodes all the bytes in the specified byte span into a string.

public:
 System::String ^ GetString(ReadOnlySpan<System::Byte> bytes);
public string GetString (ReadOnlySpan<byte> bytes);
member this.GetString : ReadOnlySpan<byte> -> string
Public Function GetString (bytes As ReadOnlySpan(Of Byte)) As String

Parameters

bytes
ReadOnlySpan<Byte>

A read-only byte span to decode to a Unicode string.

Returns

A string that contains the decoded bytes from the provided read-only span.

Remarks

The GetString method is designed to optimize performance. Instead of creating a managed byte array and then decoding it, you can instead call this method without having to create any intermediate objects.

If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the Decoder object returned by the GetDecoder method of a derived class.

See the Remarks section of the Encoding.GetChars reference topic for a discussion of decoding techniques and considerations.

Note that the precise behavior of the GetString method for a particular Encoding implementation depends on the fallback strategy defined for that Encoding object. For more information, see the "Choosing a Fallback Strategy" section of the Character Encoding in .NET topic.

Applies to

GetString(Byte*, Int32)

Source:
Encoding.cs
Source:
Encoding.cs
Source:
Encoding.cs

Important

This API is not CLS-compliant.

When overridden in a derived class, decodes a specified number of bytes starting at a specified address into a string.

public:
 System::String ^ GetString(System::Byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public string GetString (byte* bytes, int byteCount);
[System.CLSCompliant(false)]
public string GetString (byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(false)]
public string GetString (byte* bytes, int byteCount);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
member this.GetString : nativeptr<byte> * int -> string
[<System.CLSCompliant(false)>]
member this.GetString : nativeptr<byte> * int -> string
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.GetString : nativeptr<byte> * int -> string

Parameters

bytes
Byte*

A pointer to a byte array.

byteCount
Int32

The number of bytes to decode.

Returns

A string that contains the results of decoding the specified sequence of bytes.

Attributes

Exceptions

bytes is a null pointer.

byteCount is less than zero.

A fallback occurred (see Character Encoding in .NET for a complete explanation)

-and-

DecoderFallback is set to DecoderExceptionFallback.

Remarks

The GetString method is designed to optimize performance when you have a native pointer to a byte array. Instead of creating a managed byte array and then decoding it, you can instead call this method without having to create any intermediate objects.

If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the Decoder object returned by the GetDecoder method of a derived class.

See the Remarks section of the Encoding.GetChars reference topic for a discussion of decoding techniques and considerations.

Note that the precise behavior of the GetString method for a particular Encoding implementation depends on the fallback strategy defined for that Encoding object. For more information, see the "Choosing a Fallback Strategy" section of the Character Encoding in .NET topic.

See also

Applies to

GetString(Byte[], Int32, Int32)

Source:
Encoding.cs
Source:
Encoding.cs
Source:
Encoding.cs

When overridden in a derived class, decodes a sequence of bytes from the specified byte array into a string.

public:
 virtual System::String ^ GetString(cli::array <System::Byte> ^ bytes, int index, int count);
public virtual string GetString (byte[] bytes, int index, int count);
abstract member GetString : byte[] * int * int -> string
override this.GetString : byte[] * int * int -> string
Public Overridable Function GetString (bytes As Byte(), index As Integer, count As Integer) As String

Parameters

bytes
Byte[]

The byte array containing the sequence of bytes to decode.

index
Int32

The index of the first byte to decode.

count
Int32

The number of bytes to decode.

Returns

A string that contains the results of decoding the specified sequence of bytes.

Exceptions

The byte array contains invalid Unicode code points.

bytes is null.

index or count is less than zero.

-or-

index and count do not denote a valid range in bytes.

A fallback occurred (for more information, see Character Encoding in .NET)

-and-

DecoderFallback is set to DecoderExceptionFallback.

Examples

The following example reads a UTF-8 encoded string from a binary file that is represented by a FileStream object. For files that are smaller than 2,048 bytes, it reads the contents of the entire file into a byte array and calls the GetString(Byte[], Int32, Int32) method to perform the decoding. For larger files, it reads 2,048 bytes at a time into a byte array, calls the Decoder.GetCharCount(Byte[], Int32, Int32) method to determine how many characters are contained in the array, and then calls the Decoder.GetChars(Byte[], Int32, Int32, Char[], Int32) method to perform the decoding.

using System;
using System.IO;
using System.Text;

public class Example
{
   const int MAX_BUFFER_SIZE = 2048;
   static Encoding enc8 = Encoding.UTF8;
   static byte[] bytes = new byte[MAX_BUFFER_SIZE]; 

   public static void Main()
   {
      FileStream fStream = new FileStream(@".\Utf8Example.txt", FileMode.Open);
      string contents = null;
      
      // If file size is small, read in a single operation.
      if (fStream.Length <= MAX_BUFFER_SIZE) {
         int bytesRead = fStream.Read(bytes, 0, bytes.Length);
         contents = enc8.GetString(bytes, 0, bytesRead);
      }   
      // If file size exceeds buffer size, perform multiple reads.
      else {
         contents = ReadFromBuffer(fStream);
      }
      fStream.Close();
      Console.WriteLine(contents);
   }

    private static string ReadFromBuffer(FileStream fStream)
    {
        string output = String.Empty;
        Decoder decoder8 = enc8.GetDecoder();
      
        while (fStream.Position < fStream.Length) {
           int nBytes = fStream.Read(bytes, 0, bytes.Length);
           int nChars = decoder8.GetCharCount(bytes, 0, nBytes);
           char[] chars = new char[nChars];
           nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0);
           output += new String(chars, 0, nChars);                                                     
        }
        return output;
    }   
}
// The example displays the following output:
//     This is a UTF-8-encoded file that contains primarily Latin text, although it
//     does list the first twelve letters of the Russian (Cyrillic) alphabet:
//     
//     А б в г д е ё ж з и й к
//     
//     The goal is to save this file, then open and decode it as a binary stream.
Imports System.IO
Imports System.Text

Module Example
   Const MAX_BUFFER_SIZE As Integer = 2048
   
   Dim enc8 As Encoding = Encoding.UTF8
   Dim bytes(MAX_BUFFER_SIZE -1) As Byte
      
   Public Sub Main()
      Dim fStream As New FileStream(".\Utf8Example.txt", FileMode.Open)
      Dim contents As String = Nothing
      
      ' If file size is small, read in a single operation.
      If fStream.Length <= MAX_BUFFER_SIZE Then
         
         Dim bytesRead As Integer = fStream.Read(bytes, 0, bytes.Length)
         contents = enc8.GetString(bytes, 0, bytesRead)
      ' If file size exceeds buffer size, perform multiple reads.
      Else
         contents = ReadFromBuffer(fStream)
      End If
      fStream.Close()
      Console.WriteLine(contents)
   End Sub   

    Private Function ReadFromBuffer(fStream As FileStream) As String
        Dim bytes(MAX_BUFFER_SIZE) As Byte
        Dim output As String = String.Empty
        Dim decoder8 As Decoder = enc8.GetDecoder()
      
        Do While fStream.Position < fStream.Length
           Dim nBytes As Integer = fStream.Read(bytes, 0, bytes.Length)
           Dim nChars As Integer = decoder8.GetCharCount(bytes, 0, nBytes)
           Dim chars(nChars - 1) As Char
           nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0)
           output += New String(chars, 0, nChars)                                                     
        Loop
        Return output
    End Function
End Module
' The example displays the following output:
'     This is a UTF-8-encoded file that contains primarily Latin text, although it
'     does list the first twelve letters of the Russian (Cyrillic) alphabet:
'     
'     А б в г д е ё ж з и й к
'     
'     The goal is to save this file, then open and decode it as a binary stream.

The example uses the following text, which should be saved to a UTF-8 encoded file named Utf8Example.txt.

This is a UTF-8-encoded file that contains primarily Latin text, although it
does list the first twelve letters of the Russian (Cyrillic) alphabet:

А б в г д е ё ж з и й к

The goal is to save this file, then open and decode it as a binary stream.

Remarks

If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively, of a derived class.

See the Remarks section of the Encoding.GetChars reference topic for a discussion of decoding techniques and considerations.

See also

Applies to