UnauthorizedAccessException Classe

Definição

A exceção que é lançada quando o sistema operativo nega o acesso devido a um erro de E/S ou a um tipo específico de erro de segurança.

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

Exemplos

O exemplo seguinte ilustra a UnauthorizedAccessException exceção que é lançada ao tentar escrever num ficheiro de apenas leitura.

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.

Observações

Uma exceção UnauthorizedAccessException é normalmente lançada por um método que envolve uma chamada API Windows. Para encontrar as razões da exceção, examine-se o texto da propriedade do Message objeto exceção.

UnauthorizedAccessException usa o HRESULTCOR_E_UNAUTHORIZEDACCESS, que tem o valor 0x80070005.

Construtores

Name Description
UnauthorizedAccessException()

Inicializa uma nova instância da UnauthorizedAccessException classe.

UnauthorizedAccessException(SerializationInfo, StreamingContext)

Inicializa uma nova instância da UnauthorizedAccessException classe com dados serializados.

UnauthorizedAccessException(String, Exception)

Inicializa uma nova instância da UnauthorizedAccessException classe com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção.

UnauthorizedAccessException(String)

Inicializa uma nova instância da UnauthorizedAccessException classe com uma mensagem de erro especificada.

Propriedades

Name Description
Data

Obtém uma coleção de pares chave/valor que fornecem informação adicional definida pelo utilizador sobre a exceção.

(Herdado de Exception)
HelpLink

Obtém ou define um link para o ficheiro de ajuda associado a esta exceção.

(Herdado de Exception)
HResult

Recebe ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica.

(Herdado de Exception)
InnerException

Obtém a Exception instância que causou a exceção atual.

(Herdado de Exception)
Message

Recebe uma mensagem que descreve a exceção atual.

(Herdado de Exception)
Source

Obtém ou define o nome do aplicativo ou o objeto que causa o erro.

(Herdado de Exception)
StackTrace

Obtém uma representação string dos frames imediatos na stack de chamadas.

(Herdado de Exception)
TargetSite

Obtém o método que lança a exceção atual.

(Herdado de Exception)

Métodos

Name Description
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetBaseException()

Quando sobrescrito numa classe derivada, devolve o Exception que é a causa raiz de uma ou mais exceções subsequentes.

(Herdado de Exception)
GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Quando sobreposto numa classe derivada, define a SerializationInfo informação com sobre a exceção.

(Herdado de Exception)
GetType()

Obtém o tipo de execução da instância atual.

(Herdado de Exception)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Cria e devolve uma representação string da exceção atual.

(Herdado de Exception)

evento

Name Description
SerializeObjectState

Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção.

(Herdado de Exception)

Aplica-se a

Ver também