Compartir vía


UnauthorizedAccessException Clase

Definición

Excepción que se produce cuando el sistema operativo deniega el acceso debido a un error de E/S o a un tipo específico de error de seguridad.

public ref class UnauthorizedAccessException : Exception
public ref class UnauthorizedAccessException : SystemException
public class UnauthorizedAccessException : Exception
public class UnauthorizedAccessException : SystemException
[System.Serializable]
public class UnauthorizedAccessException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class UnauthorizedAccessException : SystemException
type UnauthorizedAccessException = class
    inherit Exception
type UnauthorizedAccessException = class
    inherit SystemException
[<System.Serializable>]
type UnauthorizedAccessException = class
    inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type UnauthorizedAccessException = class
    inherit SystemException
Public Class UnauthorizedAccessException
Inherits Exception
Public Class UnauthorizedAccessException
Inherits SystemException
Herencia
UnauthorizedAccessException
Herencia
UnauthorizedAccessException
Derivado
Atributos

Ejemplos

En el ejemplo siguiente se muestra la excepción UnauthorizedAccessException que se produce al intentar escribir en un archivo de solo lectura.

using System;
using System.IO;

public class Example
{
   public static void Main()
   {
      string filePath = @".\ROFile.txt";
      if (! File.Exists(filePath))
         File.Create(filePath);
      // Keep existing attributes, and set ReadOnly attribute.
      File.SetAttributes(filePath, 
                        (new FileInfo(filePath)).Attributes | FileAttributes.ReadOnly);

      StreamWriter sw = null;
      try {
         sw = new StreamWriter(filePath);
         sw.Write("Test");
      }
      catch (UnauthorizedAccessException) {
         FileAttributes attr = (new FileInfo(filePath)).Attributes;
         Console.Write("UnAuthorizedAccessException: Unable to access file. ");
         if ((attr & FileAttributes.ReadOnly) > 0)
            Console.Write("The file is read-only."); 
       }
       finally {
         if (sw != null) sw.Close();
      }   
   }
}
// The example displays the following output:
//    UnAuthorizedAccessException: Unable to access file. The file is read-only.
open System
open System.IO


let filePath = @".\ROFile.txt"
if File.Exists filePath |> not then
    File.Create filePath |> ignore
// Keep existing attributes, and set ReadOnly attribute.
File.SetAttributes(filePath, (FileInfo filePath).Attributes ||| FileAttributes.ReadOnly)

do
    use sw = new StreamWriter(filePath)
    try
        sw.Write "Test"
    with :? UnauthorizedAccessException ->
        let attr = (FileInfo filePath).Attributes
        printf "UnAuthorizedAccessException: Unable to access file. "
        if int (attr &&& FileAttributes.ReadOnly) > 0 then
            printf "The file is read-only."
// The example displays the following output:
//    UnAuthorizedAccessException: Unable to access file. The file is read-only.
Imports System.IO

Module Example
   Public Sub Main()
      Dim filePath As String = ".\ROFile.txt"
      If Not File.Exists(filePath) Then File.Create(filePath)
      ' Keep existing attributes, and set ReadOnly attribute.
      File.SetAttributes(filePath, 
                        (New FileInfo(filePath)).Attributes Or FileAttributes.ReadOnly)

      Dim sw As StreamWriter = Nothing
      Try
         sw = New StreamWriter(filePath)
         sw.Write("Test")
      Catch e As UnauthorizedAccessException
         Dim attr As FileAttributes = (New FileInfo(filePath)).Attributes
         Console.Write("UnAuthorizedAccessException: Unable to access file. ")
         If (attr And FileAttributes.ReadOnly) > 0 Then
            Console.Write("The file is read-only.") 
         End If
       Finally
         If sw IsNot Nothing Then sw.Close()
      End Try   
   End Sub
End Module
' The example displays the following output:
'   UnAuthorizedAccessException: Unable to access file. The file is read-only.

Comentarios

Normalmente, una excepción de UnauthorizedAccessException se produce mediante un método que encapsula una llamada a la API de Windows. Para encontrar los motivos de la excepción, examine el texto de la propiedad Message del objeto de excepción.

UnauthorizedAccessException usa el HRESULTCOR_E_UNAUTHORIZEDACCESS, que tiene el valor 0x80070005.

Constructores

UnauthorizedAccessException()

Inicializa una nueva instancia de la clase UnauthorizedAccessException.

UnauthorizedAccessException(SerializationInfo, StreamingContext)
Obsoletos.

Inicializa una nueva instancia de la clase UnauthorizedAccessException con datos serializados.

UnauthorizedAccessException(String)

Inicializa una nueva instancia de la clase UnauthorizedAccessException con un mensaje de error especificado.

UnauthorizedAccessException(String, Exception)

Inicializa una nueva instancia de la clase UnauthorizedAccessException con un mensaje de error especificado y una referencia a la excepción interna que es la causa de esta excepción.

Propiedades

Data

Obtiene una colección de pares clave-valor que proporcionan información adicional definida por el usuario sobre la excepción.

(Heredado de Exception)
HelpLink

Obtiene o establece un vínculo al archivo de ayuda asociado a esta excepción.

(Heredado de Exception)
HResult

Obtiene o establece HRESULT, un valor numérico codificado que se asigna a una excepción específica.

(Heredado de Exception)
InnerException

Obtiene la instancia de Exception que provocó la excepción actual.

(Heredado de Exception)
Message

Obtiene un mensaje que describe la excepción actual.

(Heredado de Exception)
Source

Obtiene o establece el nombre de la aplicación o el objeto que provoca el error.

(Heredado de Exception)
StackTrace

Obtiene una representación de cadena de los fotogramas inmediatos en la pila de llamadas.

(Heredado de Exception)
TargetSite

Obtiene el método que produce la excepción actual.

(Heredado de Exception)

Métodos

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetBaseException()

Cuando se reemplaza en una clase derivada, devuelve el Exception que es la causa principal de una o varias excepciones posteriores.

(Heredado de Exception)
GetHashCode()

Actúa como función hash predeterminada.

(Heredado de Object)
GetObjectData(SerializationInfo, StreamingContext)
Obsoletos.

Cuando se reemplaza en una clase derivada, establece el SerializationInfo con información sobre la excepción.

(Heredado de Exception)
GetType()

Obtiene el tipo de tiempo de ejecución de la instancia actual.

(Heredado de Exception)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
ToString()

Crea y devuelve una representación de cadena de la excepción actual.

(Heredado de Exception)

Eventos

SerializeObjectState
Obsoletos.

Se produce cuando se serializa una excepción para crear un objeto de estado de excepción que contiene datos serializados sobre la excepción.

(Heredado de Exception)

Se aplica a

Consulte también