File.SetAttributes(String, FileAttributes) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Устанавливает заданные атрибуты FileAttributes файла по заданному пути.
public:
static void SetAttributes(System::String ^ path, System::IO::FileAttributes fileAttributes);
public static void SetAttributes (string path, System.IO.FileAttributes fileAttributes);
static member SetAttributes : string * System.IO.FileAttributes -> unit
Public Shared Sub SetAttributes (path As String, fileAttributes As FileAttributes)
Параметры
- path
- String
Путь к файлу.
- fileAttributes
- FileAttributes
Побитовое сочетание значений перечисления.
Исключения
платформа .NET Framework и .NET версии Core старше 2.1: path
пуста, содержит только пробелы, содержит недопустимые символы или недопустимый атрибут файла.
Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе.
Параметр path
задан в недопустимом формате.
Указан недопустимый путь (например, он ведет на несопоставленный диск).
Файл не найден.
Параметр path
указывает файл, доступный только для чтения.
-или- Эта операция не поддерживается на текущей платформе.
-или-
Параметрpath
определяет каталог.
-или- У вызывающего объекта отсутствует необходимое разрешение.
Примеры
В следующем примере показаны GetAttributes
методы и SetAttributes
методы путем применения Archive
атрибутов и Hidden
атрибутов к файлу.
using namespace System;
using namespace System::IO;
using namespace System::Text;
int main()
{
String^ path = "c:\\temp\\MyTest.txt";
// Create the file if it does not exist.
if ( !File::Exists( path ) )
{
File::Create( path );
}
if ( (File::GetAttributes( path ) & FileAttributes::Hidden) == FileAttributes::Hidden )
{
// Show the file.
File::SetAttributes(path, File::GetAttributes( path ) & ~FileAttributes::Hidden);
Console::WriteLine( "The {0} file is no longer hidden.", path );
}
else
{
// Hide the file.
File::SetAttributes( path, static_cast<FileAttributes>(File::GetAttributes( path ) | FileAttributes::Hidden) );
Console::WriteLine( "The {0} file is now hidden.", path );
}
}
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
// Create the file if it does not exist.
if (!File.Exists(path))
{
File.Create(path);
}
FileAttributes attributes = File.GetAttributes(path);
if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
// Show the file.
attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
File.SetAttributes(path, attributes);
Console.WriteLine("The {0} file is no longer hidden.", path);
}
else
{
// Hide the file.
File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
Console.WriteLine("The {0} file is now hidden.", path);
}
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
}
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
' Create the file if it does not exist.
If File.Exists(path) = False Then
File.Create(path)
End If
Dim attributes As FileAttributes
attributes = File.GetAttributes(path)
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
' Show the file.
attributes = RemoveAttribute(attributes, FileAttributes.Hidden)
File.SetAttributes(path, attributes)
Console.WriteLine("The {0} file is no longer hidden.", path)
Else
' Hide the file.
File.SetAttributes(path, File.GetAttributes(path) Or FileAttributes.Hidden)
Console.WriteLine("The {0} file is now hidden.", path)
End If
End Sub
Public Shared Function RemoveAttribute(ByVal attributes As FileAttributes, ByVal attributesToRemove As FileAttributes) As FileAttributes
Return attributes And (Not attributesToRemove)
End Function
End Class
Комментарии
Параметр path
может указывать относительные или абсолютные сведения о пути. Относительные сведения о пути интерпретируются относительно текущего рабочего каталога. Сведения о получении текущего рабочего каталога см. в разделе GetCurrentDirectory.
Некоторые атрибуты файла, такие как Hidden и ReadOnly, могут быть объединены. Другие атрибуты, например Normal, должны использоваться только.
Невозможно изменить состояние File сжатия объекта с помощью SetAttributes метода.
Список распространенных задач ввода-вывода см. в разделе "Общие задачи ввода-вывода".