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 namespace System;
using namespace System::IO;

int main()
{
    // Create a temporary file.
    String^ filePath = Path::GetTempFileName();
    Console::WriteLine("Created a temp file at '{0}.", filePath);

    // Create a new FileInfo object.
    FileInfo^ fInfo = gcnew 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 '{0}' is {1}.", fInfo->Name, isReadOnly);

    // Set the file to read-only.
    Console::WriteLine("Setting the read-only value for '{0}' to true.", fInfo->Name);
    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 '{0}' is {1}.", fInfo->Name, isReadOnly);

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

    // Delete the temporary file.
    fInfo->Delete();

    return 0;
};

// 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.
//
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 , чтобы получить последнюю копию сведений.

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