Evaluar y enviar comentarios
MSDN
MSDN Library
 ZeroFreeCoTaskMemAnsi (Método)
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2005/.NET Framework 2.0

Hay además otras versiones disponibles para:
Biblioteca de clases de .NET Framework
Marshal.ZeroFreeCoTaskMemAnsi (Método)

Nota: este método es nuevo en la versión 2.0 de .NET Framework.

Libera un puntero a una cadena no administrada que se ha asignado con el método SecureStringToCoTaskMemAnsi.

Espacio de nombres: System.Runtime.InteropServices
Ensamblado: mscorlib (en mscorlib.dll)

Visual Basic (Declaración)
Public Shared Sub ZeroFreeCoTaskMemAnsi ( _
    s As IntPtr _
)
Visual Basic (Uso)
Dim s As IntPtr

Marshal.ZeroFreeCoTaskMemAnsi(s)
C#
public static void ZeroFreeCoTaskMemAnsi (
    IntPtr s
)
C++
public:
static void ZeroFreeCoTaskMemAnsi (
    IntPtr s
)
J#
public static void ZeroFreeCoTaskMemAnsi (
    IntPtr s
)
JScript
public static function ZeroFreeCoTaskMemAnsi (
    s : IntPtr
)

Parámetros

s

La dirección de la cadena no administrada que se va a liberar.

El método ZeroFreeCoTaskMemAnsi primero hace que el resultado sea cero y luego libera memoria no administrada que se ha asignado con el método SecureStringToCoTaskMemAnsi.

NotaNota

Este método utiliza SecurityAction.LinkDemand para evitar que se le llame desde código que no sea de confianza; sólo el llamador inmediato debe disponer del permiso SecurityPermissionAttribute.UnmanagedCode. Si se puede llamar al código desde código de confianza parcial, no pase ninguna entrada de usuario a los métodos de la clase Marshal sin validación. Para conocer las limitaciones importantes que existen a la hora de utilizar el miembro LinkDemand, vea Demand frente a LinkDemand.

En el siguiente ejemplo de código se utiliza el método SecureStringToCoTaskMemAnsi para calcular referencias y descifrar el contenido de un objeto SecureString en un bloque de memoria no administrada. A continuación se utiliza el método ZeroFreeCoTaskMemAnsi para hacer que el resultado sea cero y desechar el bloque no administrado.

Visual Basic
Imports System
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports System.Security
Imports System.Security.Principal
Imports System.Text




Module MarshalExample



    Sub Main(ByVal args() As String)

        Dim unmanagedRef As IntPtr

        Try
            ' Ask the user for a password.
            Console.Write("Please enter your password:")

            Dim passWord As SecureString = GetPassword()

            Console.WriteLine("Copying and decrypting the string to unmanaged memory...")

            ' Copy the Secure string to unmanaged memory (and decrypt it).
            unmanagedRef = Marshal.SecureStringToCoTaskMemAnsi(passWord)


        Catch e As Exception
            Console.WriteLine(e.Message)
        Finally

            If unmanagedRef <> IntPtr.Size Then

                Console.WriteLine("Zeroing out unmanaged memory...")

                Marshal.ZeroFreeCoTaskMemAnsi(unmanagedRef)

            End If

        End Try

        Console.WriteLine("Done.")

        Console.ReadLine()

    End Sub



    Function GetPassword() As SecureString
        Dim password As New SecureString()

        ' get the first character of the password
        Dim nextKey As ConsoleKeyInfo = Console.ReadKey(True)

        While nextKey.Key <> ConsoleKey.Enter
            If nextKey.Key = ConsoleKey.BackSpace Then
                If password.Length > 0 Then
                    password.RemoveAt(password.Length - 1)

                    ' erase the last * as well
                    Console.Write(nextKey.KeyChar)
                    Console.Write(" ")
                    Console.Write(nextKey.KeyChar)
                End If
            Else
                password.AppendChar(nextKey.KeyChar)
                Console.Write("*")
            End If

            nextKey = Console.ReadKey(True)
        End While

        Console.WriteLine()

        ' lock the password down
        password.MakeReadOnly()
        Return password

    End Function
End Module
C#
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Text;

namespace SecureStringExample
{

    class MarshalExample
    {


        static void Main(string[] args)
        {
            IntPtr unmanagedRef = IntPtr.Zero;

            try
            {
                // Ask the user for a password.
                Console.Write("Please enter your password:");

                SecureString passWord = GetPassword();

                Console.WriteLine("Copying and decrypting the string to unmanaged memory...");

                // Copy the Secure string to unmanaged memory (and decrypt it).
                unmanagedRef = Marshal.SecureStringToCoTaskMemAnsi(passWord);


            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                if (unmanagedRef != IntPtr.Zero)
                {
                    Console.WriteLine("Zeroing out unmanaged memory...");

                    Marshal.ZeroFreeCoTaskMemAnsi(unmanagedRef);
                }

            }

            Console.WriteLine("Done.");

            Console.ReadLine();


        }

        public static SecureString GetPassword()
        {
            SecureString password = new SecureString();

            // get the first character of the password
            ConsoleKeyInfo nextKey = Console.ReadKey(true);

            while (nextKey.Key != ConsoleKey.Enter)
            {
                if (nextKey.Key == ConsoleKey.Backspace)
                {
                    if (password.Length > 0)
                    {
                        password.RemoveAt(password.Length - 1);

                        // erase the last * as well
                        Console.Write(nextKey.KeyChar);
                        Console.Write(" ");
                        Console.Write(nextKey.KeyChar);
                    }
                }
                else
                {
                    password.AppendChar(nextKey.KeyChar);
                    Console.Write("*");
                }

                nextKey = Console.ReadKey(true);
            }

            Console.WriteLine();

            // lock the password down
            password.MakeReadOnly();
            return password;
        }
    }
}

Windows 98, Windows 2000 SP4, Windows Millennium, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

.NET Framework

Compatible con: 2.0
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker