Как удалить один атрибут (например, ReadOnly) из файла?
Скажем, файл имеет следующие атрибуты: ReadOnly, Hidden, Archived, System
. Как удалить только один атрибут? (например, ReadOnly)
Если я использую:
Io.File.SetAttributes("File.txt",IO.FileAttributes.Normal)
он удаляет все атрибуты.
- Эквивалент chmod для изменения прав доступа к файлам в Windows
- Эквивалент chmod для изменения прав доступа к файлам в Windows
- Использование VBA для получения расширенных атрибутов файла
- Расшифровать файлы EFS
Из MSDN : вы можете удалить любой атрибут, подобный этому
(но ответ @ sll для просто ReadOnly лучше всего подходит именно для этого атрибута)
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 exists. if (!File.Exists(path)) { File.Create(path); } FileAttributes attributes = File.GetAttributes(path); if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // Make the file RW attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly); File.SetAttributes(path, attributes); Console.WriteLine("The {0} file is no longer RO.", path); } else { // Make the file RO File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden); Console.WriteLine("The {0} file is now RO.", path); } } private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove) { return attributes & ~attributesToRemove; } }
Ответ на ваш вопрос в заголовке относительно атрибута ReadOnly
:
FileInfo fileInfo = new FileInfo(pathToAFile); fileInfo.IsReadOnly = false;
Чтобы получить контроль над любым атрибутом, вы можете использовать File.SetAttributes()
. Примером может служить ссылка.
string file = "file.txt"; FileAttributes attrs = File.GetAttributes(file); if (attrs.HasFlag(FileAttributes.ReadOnly)) File.SetAttributes(file, attrs & ~FileAttributes.ReadOnly);
if ((oFileInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) oFileInfo.Attributes ^= FileAttributes.ReadOnly;
Для решения одной строки (при условии, что текущий пользователь имеет доступ к изменению атрибутов упомянутого файла), вот как я это сделал:
VB.Net
Shell("attrib file.txt -r")
отрицательный знак означает remove
а r
– только для чтения. если вы хотите удалить другие атрибуты, вы должны:
Shell("attrib file.txt -r -s -h -a")
Это приведет к удалению атрибутов Read-Only, System-File, Hidden и Archive.
если вы хотите вернуть эти атрибуты, вот как это сделать:
Shell("attrib file.txt +r +s +h +a")
порядок не имеет значения.
C #
Process.Start("cmd.exe", "attrib file.txt +r +s +h +a");
Рекомендации
- ComputerHope.com – множество примеров и примечаний к ОС
- Microsoft – Страница для XP, но, вероятно, относится к более поздним версиям
- Википедия – в частности раздел «Особенности»
/// /// Addes the given FileAttributes to the given File. /// It's possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly /// public static void AttributesSet(this FileInfo pFile, FileAttributes pAttributes) { pFile.Attributes = pFile.Attributes | pAttributes; pFile.Refresh(); } /// /// Removes the given FileAttributes from the given File. /// It's possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly /// public static void AttributesRemove(this FileInfo pFile, FileAttributes pAttributes) { pFile.Attributes = pFile.Attributes & ~pAttributes; pFile.Refresh(); } /// /// Checks the given File on the given Attributes. /// It's possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly /// /// True if any Attribute is set, False if non is set public static bool AttributesIsAnySet(this FileInfo pFile, FileAttributes pAttributes) { return ((pFile.Attributes & pAttributes) > 0); } /// /// Checks the given File on the given Attributes. /// It's possible to combine FileAttributes: FileAttributes.Hidden | FileAttributes.ReadOnly /// /// True if all Attributes are set, False if any is not set public static bool AttributesIsSet(this FileInfo pFile, FileAttributes pAttributes) { return (pAttributes == (pFile.Attributes & pAttributes)); }
Пример:
private static void Test() { var lFileInfo = new FileInfo(@"C:\Neues Textdokument.txt"); lFileInfo.AttributesSet(FileAttributes.Hidden | FileAttributes.ReadOnly); lFileInfo.AttributesSet(FileAttributes.Temporary); var lBool1 = lFileInfo.AttributesIsSet(FileAttributes.Hidden); var lBool2 = lFileInfo.AttributesIsSet(FileAttributes.Temporary); var lBool3 = lFileInfo.AttributesIsSet(FileAttributes.Encrypted); var lBool4 = lFileInfo.AttributesIsSet(FileAttributes.ReadOnly | FileAttributes.Temporary); var lBool5 = lFileInfo.AttributesIsSet(FileAttributes.ReadOnly | FileAttributes.Encrypted); var lBool6 = lFileInfo.AttributesIsAnySet(FileAttributes.ReadOnly | FileAttributes.Temporary); var lBool7 = lFileInfo.AttributesIsAnySet(FileAttributes.ReadOnly | FileAttributes.Encrypted); var lBool8 = lFileInfo.AttributesIsAnySet(FileAttributes.Encrypted); lFileInfo.AttributesRemove(FileAttributes.Temporary); lFileInfo.AttributesRemove(FileAttributes.Hidden | FileAttributes.ReadOnly); }
Использовать это:
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
Подробнее читайте в MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.setattributes.aspx