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


FileInfo.IsReadOnly Свойство

Определение

Возвращает или задает значение, определяющее, доступен ли текущий файл только для чтения.

public:
 property bool IsReadOnly { bool get(); void set(bool value); };
public bool IsReadOnly { get; set; }
member this.IsReadOnly : bool with get, set
Public Property IsReadOnly As Boolean

Значение свойства

true Значение , если текущий файл доступен только для чтения или не найден; falseв противном случае .

Исключения

Файл, описанный текущим FileInfo объектом, не удалось найти при попытке задать свойство IsReadOnly. (Обратите внимание, что получение этого свойства для несуществующего файла не вызывает исключение, а возвращает true.)

При открытии файла произошла ошибка ввода-вывода.

Эта операция не поддерживается на текущей платформе.

–или–

Вызывающий объект не имеет требуемого разрешения.

Пользователь не имеет разрешения на запись, но попытался задать для этого свойства значение false.

Примеры

В следующем примере создается временный файл, используется IsReadOnly свойство для первой проверки и последующего задания состояния только для чтения и, наконец, помечает его как запись для чтения, чтобы удалить его.

using System;
using System.IO;

public class FileExample
{
    public static void Main()
    {
        // Create a temporary file.
        string filePath = Path.GetTempFileName();
        Console.WriteLine($"Created a temp file at '{filePath}'.");

        // Create a new FileInfo object.
        FileInfo fInfo = new FileInfo(filePath);

        // Get the read-only value for a file.
        bool isReadOnly = fInfo.IsReadOnly;

        // Display whether the file is read-only.
        Console.WriteLine($"The file read-only value for '{fInfo.Name}' is {isReadOnly}.");

        // Set the file to read-only.        
        Console.WriteLine($"Setting the read-only value for '{fInfo.Name}' to true.");
        fInfo.IsReadOnly = true;

        // Get the read-only value for a file.
        isReadOnly = fInfo.IsReadOnly;

        // Display that the file is now read-only.
        Console.WriteLine($"The file read-only value for '{fInfo.Name}' is {isReadOnly}.");

        // Make the file mutable again so it can be deleted.
        fInfo.IsReadOnly = false;

        // Delete the temporary file.
        fInfo.Delete();
    }
}

// This code produces output similar to the following,
// though results may vary based on the computer, file structure, etc.:
//
// Created a temp file at 'C:\Users\UserName\AppData\Local\Temp\tmpB438.tmp'.
// The file read-only value for 'tmpB438.tmp' is False.
// Setting the read-only value for 'tmpB438.tmp' to true.
// The file read-only value for 'tmpB438.tmp' is True.
//
Imports System.IO

Module FileExample

    Sub Main()

        ' Create a temporary file.
        Dim filePath As String = Path.GetTempFileName()
        Console.WriteLine($"Created a temp file at '{filePath}'.")

        ' Create a new FileInfo object.
        Dim fInfo As New FileInfo(filePath)

        ' Get the read-only value for a file.
        Dim isReadOnly As Boolean = fInfo.IsReadOnly

        ' Display whether the file is read-only.
        Console.WriteLine($"The file read-only value for '{fInfo.Name}' is {isReadOnly}.")

        ' Set the file to read-only.
        Console.WriteLine($"Setting the read-only value for '{fInfo.Name}' to true.")
        fInfo.IsReadOnly = True

        ' Get the read-only value for a file.
        isReadOnly = fInfo.IsReadOnly

        ' Display that the file is now read-only.
        Console.WriteLine($"The file read-only value for '{fInfo.Name}' is {isReadOnly}.")

        ' Make the file mutable again so it can be deleted.
        fInfo.IsReadOnly = False

        ' Delete the temporary file.
        fInfo.Delete()
    End Sub

End Module

' This code produces output similar to the following,
' though results may vary based on the computer, file structure, etc.:
'
' Created a temp file at 'C:\Users\UserName\AppData\Local\Temp\tmpB438.tmp'.
' The file read-only value for 'tmpB438.tmp' is False.
' Setting the read-only value for 'tmpB438.tmp' to true.
' The file read-only value for 'tmpB438.tmp' is True.
'

Комментарии

IsReadOnly Используйте свойство, чтобы быстро определить или изменить, доступен ли текущий файл только для чтения.

Если текущий файл не существует, получение этого свойства всегда возвращается true, но попытки задать вызовет FileNotFoundExceptionисключение.

При первом вызове FileInfo вызовы Refresh и кэширование сведений о файле. При последующих вызовах необходимо вызвать Refresh последнюю копию информации.

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