FileAttributes Перечисление
Определение
Предоставляет атрибуты для файлов и каталогов.Provides attributes for files and directories.
Это перечисление имеет атрибут FlagsAttribute, который разрешает побитовое сочетание значений его элементов.
public enum class FileAttributes
[System.Flags]
public enum FileAttributes
[System.Flags]
[System.Serializable]
public enum FileAttributes
[System.Flags]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum FileAttributes
[<System.Flags>]
type FileAttributes =
[<System.Flags>]
[<System.Serializable>]
type FileAttributes =
[<System.Flags>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type FileAttributes =
Public Enum FileAttributes
- Наследование
- Атрибуты
Поля
Archive | 32 | Этот файл помечается для включения в операцию добавочного резервного копирования.This file is marked to be included in incremental backup operation. Windows устанавливает этот атрибут при каждом изменении файла, и программному обеспечению резервного копирования нужно снимать его при обработке файла в рамках добавочного резервного копирования.Windows sets this attribute whenever the file is modified, and backup software should clear it when processing the file during incremental backup. |
Compressed | 2048 | Файл сжат.The file is compressed. |
Device | 64 | Зарезервировано для будущего использования.Reserved for future use. |
Directory | 16 | Файл является каталогом.The file is a directory. |
Encrypted | 16384 | Файл или каталог зашифрован.The file or directory is encrypted. Для файла это означает, что все данные в файле зашифрованы.For a file, this means that all data in the file is encrypted. Для каталога это означает, что шифрование производится по умолчанию для вновь создаваемых файлов и каталогов.For a directory, this means that encryption is the default for newly created files and directories. |
Hidden | 2 | Файл скрытый и, таким образом, не включается в обычный список каталога.The file is hidden, and thus is not included in an ordinary directory listing. |
IntegrityStream | 32768 | Файл или каталог включает поддержку целостности данных.The file or directory includes data integrity support. Когда это значение применяется к файлу, все потоки данных в этом файле имеют поддержку целостности.When this value is applied to a file, all data streams in the file have integrity support. Когда это значение применяется к каталогу, все новые файлы и подкаталоги этого каталога по умолчанию включают поддержку целостности.When this value is applied to a directory, all new files and subdirectories within that directory, by default, include integrity support. |
Normal | 128 | Файл является стандартным файлом без специальных атрибутов.The file is a standard file that has no special attributes. Этот атрибут действителен, только если он используется отдельно.This attribute is valid only if it is used alone. |
NoScrubData | 131072 | Файл или каталог исключен из проверки целостности данных.The file or directory is excluded from the data integrity scan. Когда это значение применяется к каталогу, по умолчанию для всех новых файлов и подкаталогов этого каталога поддержка целостности исключается.When this value is applied to a directory, by default, all new files and subdirectories within that directory are excluded from data integrity. |
NotContentIndexed | 8192 | Файл не будет индексироваться службой индексирования содержимого операционной системы.The file will not be indexed by the operating system's content indexing service. |
Offline | 4096 | Файл находится в автономном режиме.The file is offline. Данные этого файла недоступны непосредственно.The data of the file is not immediately available. |
ReadOnly | 1 | Файл доступен только для чтения.The file is read-only. |
ReparsePoint | 1024 | Файл содержит точку повторной обработки, блокирующую определяемые пользователем данные, связанные с файлом или каталогом.The file contains a reparse point, which is a block of user-defined data associated with a file or a directory. |
SparseFile | 512 | Файл является разреженным.The file is a sparse file. Разреженными файлами обычно являются большие файлы, в которых содержатся в основном нулевые данные.Sparse files are typically large files whose data consists of mostly zeros. |
System | 4 | Файл является системным.The file is a system file. То есть файл является частью операционной системы или используется исключительно операционной системой.That is, the file is part of the operating system or is used exclusively by the operating system. |
Temporary | 256 | Файл является временным.The file is temporary. Временный файл содержит данные, необходимые во время выполнения приложения, но не требуемые после завершения приложения.A temporary file contains data that is needed while an application is executing but is not needed after the application is finished. Файловые системы для ускорения доступа стремятся держать все данные в памяти, а не сбрасывать их обратно на запоминающее устройство.File systems try to keep all the data in memory for quicker access rather than flushing the data back to mass storage. Приложение должно стереть временный файл сразу после того, как он перестанет быть нужным.A temporary file should be deleted by the application as soon as it is no longer needed. |
Примеры
В следующем примере показано, как получить атрибуты для файла и проверить, доступен ли файл только для чтения.The following example shows how to retrieve the attributes for a file and check if the file is read-only.
using System;
using System.IO;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
FileAttributes attributes = File.GetAttributes("c:/Temp/testfile.txt");
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
Console.WriteLine("read-only file");
}
else
{
Console.WriteLine("not read-only file");
}
}
}
}
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
Dim attributes = File.GetAttributes("c:/Temp/testfile.txt")
If ((attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly) Then
Console.WriteLine("read-only file")
Else
Console.WriteLine("not read-only file")
End If
End Sub
End Module
Комментарии
Вы можете получить атрибуты для файлов и каталогов, вызвав File.GetAttributes метод, и вы можете задать их, вызвав File.SetAttributes метод.You can get attributes for files and directories by calling the File.GetAttributes method, and you can set them by calling the File.SetAttributes method.
Невозможно изменить состояние сжатия File объекта с помощью File.SetAttributes метода.It is not possible to change the compression status of a File object by using the File.SetAttributes method. Вместо этого необходимо сжать файл с помощью средства сжатия или одного из классов в System.IO.Compression пространстве имен.Instead, you must actually compress the file using either a compression tool or one of the classes in the System.IO.Compression namespace.
Следующие атрибуты не поддерживаются .NET Core в Linux и macOS:The following attributes are not supported by .NET Core on Linux and macOS:
- FileAttributes.Archive
- FileAttributes.Compressed
- FileAttributes.Device
- FileAttributes.Encrypted
- FileAttributes.IntegrityStream
- FileAttributes.NoScrubData
- FileAttributes.NotContentIndexed
- FileAttributes.Offline
- FileAttributes.SparseFile
- FileAttributes.System
- FileAttributes.Temporary
В системах UNIX значение, возвращаемое функцией, File.GetAttributes включает Hidden
для файла, имя которого начинается с точки (".").On Unix systems, the value returned by File.GetAttributes includes Hidden
for a file whose name begins with a period ("."). В macOS можно получить или задать скрытый флаг.On macOS, you can get or set the hidden flag.