Прочитать на английском

Поделиться через


ToBase64Transform Класс

Определение

Преобразует CryptoStream в кодировку base64.

public class ToBase64Transform : IDisposable, System.Security.Cryptography.ICryptoTransform
public class ToBase64Transform : System.Security.Cryptography.ICryptoTransform
[System.Runtime.InteropServices.ComVisible(true)]
public class ToBase64Transform : System.Security.Cryptography.ICryptoTransform
Наследование
ToBase64Transform
Атрибуты
Реализации

Примеры

В следующем примере кода показано, как использовать члены ToBase64Transform класса .

using System;
using System.IO;
using System.Security.Cryptography;

class Members
{
    [STAThread]
    static void Main(string[] args)
    {
        string appPath = (System.IO.Directory.GetCurrentDirectory() + "\\");

        // Insert your file names into this method call.
        EncodeFromFile(appPath + "members.cs", appPath + "members.enc");

        Console.WriteLine("This sample completed successfully; " +
            "press Enter to exit.");
        Console.ReadLine();
    }

    // Read in the specified source file and write out an encoded target file.
    private static void EncodeFromFile(string sourceFile, string targetFile) 
    {
        // Verify members.cs exists at the specified directory.
        if (!File.Exists(sourceFile))
        {
            Console.Write("Unable to locate source file located at ");
            Console.WriteLine(sourceFile + ".");
            Console.Write("Please correct the path and run the ");
            Console.WriteLine("sample again.");
            return;
        }

        // Retrieve the input and output file streams.
        FileStream inputFileStream = 
            new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
        FileStream outputFileStream = 
            new FileStream(targetFile, FileMode.Create, FileAccess.Write);

        // Create a new ToBase64Transform object to convert to base 64.
        ToBase64Transform base64Transform = new ToBase64Transform();

        // Create a new byte array with the size of the output block size.
        byte[] outputBytes = new byte[base64Transform.OutputBlockSize];

        // Retrieve the file contents into a byte array.
        byte[] inputBytes = new byte[inputFileStream.Length];
        inputFileStream.Read(inputBytes, 0, inputBytes.Length);

        // Verify that multiple blocks can not be transformed.
        if (!base64Transform.CanTransformMultipleBlocks)
        {
            // Initializie the offset size.
            int inputOffset = 0;

            // Iterate through inputBytes transforming by blockSize.
            int inputBlockSize = base64Transform.InputBlockSize;

            while(inputBytes.Length - inputOffset > inputBlockSize)
            {
                base64Transform.TransformBlock(
                    inputBytes,
                    inputOffset,
                    inputBytes.Length - inputOffset,
                    outputBytes,
                    0);

                inputOffset += base64Transform.InputBlockSize;
                outputFileStream.Write(
                    outputBytes, 
                    0, 
                    base64Transform.OutputBlockSize);
            }

            // Transform the final block of data.
            outputBytes = base64Transform.TransformFinalBlock(
                inputBytes,
                inputOffset,
                inputBytes.Length - inputOffset);

            outputFileStream.Write(outputBytes, 0, outputBytes.Length);
            Console.WriteLine("Created encoded file at " + targetFile);
        }

        // Determine if the current transform can be reused.
        if (!base64Transform.CanReuseTransform)
        {
            // Free up any used resources.
            base64Transform.Clear();
        }

        // Close file streams.
        inputFileStream.Close();
        outputFileStream.Close();
    }
}
//
// This sample produces the following output:
//
// Created encoded file at C:\ConsoleApplication1\\membersvcs.enc
// This sample completed successfully; press Enter to exit.

Комментарии

Base 64 Content-Transfer-Encoding представляет произвольные битовые последовательности в форме, которая недоступна для чтения человеком.

Конструкторы

ToBase64Transform()

Инициализирует новый экземпляр класса ToBase64Transform.

Свойства

CanReuseTransform

Получает значение, указывающее на возможность повторного использования текущего преобразования.

CanTransformMultipleBlocks

Возвращает значение, указывающее на возможность преобразования нескольких блоков.

InputBlockSize

Возвращает размер входного блока.

OutputBlockSize

Возвращает размер выходного блока.

Методы

Clear()

Освобождает все ресурсы, занятые модулем ToBase64Transform.

Dispose()

Освобождает все ресурсы, используемые текущим экземпляром класса ToBase64Transform.

Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые объектом ToBase64Transform, а при необходимости освобождает также управляемые ресурсы.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
Finalize()

Освобождает неуправляемые ресурсы, используемые ToBase64Transform.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)
TransformBlock(Byte[], Int32, Int32, Byte[], Int32)

Преобразует заданную область входного массива байтов в кодировку base64 и копирует результат в заданную область выходного массива байтов.

TransformFinalBlock(Byte[], Int32, Int32)

Преобразует заданную область заданного массива байтов в кодировку base64.

Явные реализации интерфейса

IDisposable.Dispose()

Освобождает неуправляемые ресурсы, используемые ToBase64Transform.

Применяется к

Продукт Версии
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

См. также раздел