UnauthorizedAccessException Classe
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
A exceção gerada quando o sistema operacional nega o acesso devido a um erro de E/S ou um tipo específico de erro de segurança.
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
- Herança
- Herança
- Derivado
- Atributos
O exemplo a seguir ilustra a exceção UnauthorizedAccessException gerada ao tentar gravar em um arquivo somente 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.
Uma exceção UnauthorizedAccessException normalmente é gerada por um método que encapsula uma chamada à API do Windows. Para localizar os motivos da exceção, examine o texto da propriedade Message do objeto de exceção.
UnauthorizedAccessException usa o HRESULT
COR_E_UNAUTHORIZEDACCESS
, que tem o valor 0x80070005.
Unauthorized |
Inicializa uma nova instância da classe UnauthorizedAccessException. |
Unauthorized |
Obsoleto.
Inicializa uma nova instância da classe UnauthorizedAccessException com dados serializados. |
Unauthorized |
Inicializa uma nova instância da classe UnauthorizedAccessException com uma mensagem de erro especificada. |
Unauthorized |
Inicializa uma nova instância da classe UnauthorizedAccessException com uma mensagem de erro especificada e uma referência à exceção interna que é a causa dessa exceção. |
Data |
Obtém uma coleção de pares chave/valor que fornecem informações adicionais definidas pelo usuário sobre a exceção. (Herdado de Exception) |
Help |
Obtém ou define um link para o arquivo de ajuda associado a essa exceção. (Herdado de Exception) |
HResult |
Obtém ou define HRESULT, um valor numérico codificado atribuído a uma exceção específica. (Herdado de Exception) |
Inner |
Obtém a instância de Exception que causou a exceção atual. (Herdado de Exception) |
Message |
Obtém uma mensagem que descreve a exceção atual. (Herdado de Exception) |
Source |
Obtém ou define o nome do aplicativo ou do objeto que causa o erro. (Herdado de Exception) |
Stack |
Obtém uma representação de cadeia de caracteres dos quadros imediatos na pilha de chamadas. (Herdado de Exception) |
Target |
Obtém o método que gera a exceção atual. (Herdado de Exception) |
Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
Get |
Quando substituído em uma classe derivada, retorna o Exception que é a causa raiz de uma ou mais exceções subsequentes. (Herdado de Exception) |
Get |
Serve como a função de hash padrão. (Herdado de Object) |
Get |
Obsoleto.
Quando substituído em uma classe derivada, define o SerializationInfo com informações sobre a exceção. (Herdado de Exception) |
Get |
Obtém o tipo de runtime da instância atual. (Herdado de Exception) |
Memberwise |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
To |
Cria e retorna uma representação de cadeia de caracteres da exceção atual. (Herdado de Exception) |
Serialize |
Obsoleto.
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) |
Produto | Versões |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.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 | 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1 |
UWP | 10.0 |
- Exception
- de tratamento e geração de exceções
Comentários do .NET
O .NET é um projeto código aberto. Selecione um link para fornecer comentários: