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.
При открытии файла произошла ошибка ввода-вывода.
Эта операция не поддерживается на текущей платформе.
-или-
У вызывающего объекта отсутствует необходимое разрешение.
Пользователь не имеет разрешения на запись, но пытается задать для этого свойства значение false
.
Примеры
В следующем примере свойство помечает IsReadOnly файл как доступный только для чтения, а затем помечает его как чтение и запись.
using namespace System;
using namespace System::IO;
namespace FileSystemExample
{
// Sets the read-only value of a file.
void SetFileReadAccess(String^ fileName, bool setReadOnly)
{
// Create a new FileInfo object.
FileInfo^ fInfo = gcnew FileInfo(fileName);
// Set the IsReadOnly property.
fInfo->IsReadOnly = setReadOnly;
}
// Returns whether a file is read-only.
bool IsFileReadOnly(String^ fileName)
{
// Create a new FileInfo object.
FileInfo^ fInfo = gcnew FileInfo(fileName);
// Return the IsReadOnly property value.
return fInfo->IsReadOnly;
}
}
int main()
{
try
{
String^ fileName = "c:\\test.xml";
if (File::Exists(fileName))
{
// Get the read-only value for a file.
bool isReadOnly = FileSystemExample::IsFileReadOnly(fileName);
// Display whether the file is read-only.
Console::WriteLine("The file read-only value for {0} is:" +
"{1}", fileName, isReadOnly);
Console::WriteLine("Changing the read-only value for {0}" +
" to true.", fileName);
// Set the file to read-only.
FileSystemExample::SetFileReadAccess(fileName, true);
// Get the read-only value for a file.
isReadOnly = FileSystemExample::IsFileReadOnly(fileName);
// Display that the file is read-only.
Console::WriteLine("The file read-only value for {0} is:" +
"{1}", fileName, isReadOnly);
}
else
{
Console::WriteLine("The file {0} doesn't exist.", fileName);
}
}
catch (IOException^ ex)
{
Console::WriteLine(ex->Message);
}
};
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//The file read-only value for c:\test.xml is:False
//Changing the read-only value for c:\test.xml to true.
//The file read-only value for c:\test.xml is:True
using System;
using System.IO;
namespace FileSystemExample
{
class FileExample
{
public static void Main()
{
string FileName = @"c:\test.xml";
// Get the read-only value for a file.
bool isReadOnly = IsFileReadOnly(FileName);
// Display wether the file is read-only.
Console.WriteLine("The file read-only value for " + FileName + " is: " + isReadOnly);
Console.WriteLine("Changing the read-only value for " + FileName + " to true.");
// Set the file to read-only.
SetFileReadAccess(FileName, true);
// Get the read-only value for a file.
isReadOnly = IsFileReadOnly(FileName);
// Display that the file is read-only.
Console.WriteLine("The file read-only value for " + FileName + " is: " + isReadOnly);
}
// Sets the read-only value of a file.
public static void SetFileReadAccess(string FileName, bool SetReadOnly)
{
// Create a new FileInfo object.
FileInfo fInfo = new FileInfo(FileName);
// Set the IsReadOnly property.
fInfo.IsReadOnly = SetReadOnly;
}
// Returns wether a file is read-only.
public static bool IsFileReadOnly(string FileName)
{
// Create a new FileInfo object.
FileInfo fInfo = new FileInfo(FileName);
// Return the IsReadOnly property value.
return fInfo.IsReadOnly;
}
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//The file read-only value for c:\test.xml is: True
//Changing the read-only value for c:\test.xml to true.
//The file read-only value for c:\test.xml is: True
//
Imports System.IO
Module FileExample
Sub Main()
Dim FileName As String = "c:\test.xml"
' Get the read-only value for a file.
Dim isReadOnly As Boolean = IsFileReadOnly(FileName)
' Display wether the file is read-only.
Console.WriteLine("The file read-only value for " & FileName & " is: " & isReadOnly)
Console.WriteLine("Changing the read-only value for " & FileName & " to true.")
' Set the file to read-only.
SetFileReadAccess(FileName, True)
' Get the read-only value for a file.
isReadOnly = IsFileReadOnly(FileName)
' Display that the file is read-only.
Console.WriteLine("The file read-only value for " & FileName & " is: " & isReadOnly)
End Sub
' Sets the read-only value of a file.
Sub SetFileReadAccess(ByVal FileName As String, ByVal SetReadOnly As Boolean)
' Create a new FileInfo object.
Dim fInfo As New FileInfo(FileName)
' Set the IsReadOnly property.
fInfo.IsReadOnly = SetReadOnly
End Sub
' Returns wether a file is read-only.
Function IsFileReadOnly(ByVal FileName As String) As Boolean
' Create a new FileInfo object.
Dim fInfo As New FileInfo(FileName)
' Return the IsReadOnly property value.
Return fInfo.IsReadOnly
End Function
End Module
'This code produces output similar to the following;
'results may vary based on the computer/file structure/etc.:
'
'The file read-only value for c:\test.xml is: True
'Changing the read-only value for c:\test.xml to true.
'The file read-only value for c:\test.xml is: True
Комментарии
IsReadOnly Используйте свойство, чтобы быстро определить или изменить, доступен ли текущий файл только для чтения.
При первом вызове FileInfo вызовы Refresh и кэширование сведений о файле. При последующих звонках необходимо вызвать Refresh , чтобы получить последнюю копию информации.