枚举2-文件属性
1 using System; 2 3 namespace EnumFlagAttribute 4 { 5 // 尽可能使用显示赋值定义的基本类型 6 // 加上Flags,如果用户输入为3,则可以把File.ReadOnly属性和File.Hidden属性解析出来。 7 // 如果不加,用户输入为1时,还能正常解析,即为File.ReadOnly属性,如果此时用户输入为3,则解析不了,也可能依旧是3。 8 [Flags] 9 enum FileAttributes 10 { 11 // 如果判定一个文件有没有这个属性,而不影响其他属性。则: 12 // File.Attribute &=FileAttributes.ReadOnly是否等于他本身FileAttributes.ReadOnly。//一个数&另一个数,实际上等于最小的那个数。 13 // 如果强制取消一个文件的某个属性,而不影响其他属性。则: 14 // File.Attribute &= ~FileAttributes.ReadOnly。 15 // 如果强制为文件赋予某个属性,而不影响其他属性。则: 16 // File.Attribute |=FileAttributes.ReadOnly。 17 ReadOnly = 1 << 0, // 000000000000001 18 Hidden = 1 << 1, // 000000000000010 19 System = 1 << 2, // 000000000000100 20 Directory = 1 << 4, // 000000000010000 21 Archive = 1 << 5,// 存档 // 000000000100000 22 Device = 1 << 6, // 000000001000000 23 Normal = 1 << 7, // 000000010000000 24 Temporary = 1 << 8, // 000000100000000 25 SparseFile = 1 << 9, // 000001000000000 26 ReparsePoint = 1 << 10, // 000010000000000 27 Compressed = 1 << 1, // 000100000000000 28 OffLine = 1 << 12, // 001000000000000 29 NotContentIndexed = 1 << 13, // 010000000000000 30 Encrypted = 1 << 14, // 100000000000000 31 A = ReadOnly | Hidden // 可以把这些属性组合起来,使用更方便。 32 // 可以用于文件的属性判定,除此之外,还可以用于字体的格式。 33 } 34 }
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 7 namespace EnumFlagAttribute 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 string fileName = @"enumtest.txt"; 14 FileInfo file = new FileInfo(fileName); 15 16 file.Attributes = System.IO.FileAttributes.Hidden | System.IO.FileAttributes.ReadOnly | System.IO.FileAttributes.System; 17 18 // 用移位运算来显示文件的属性,可以把文件的几个属性组合到一起,在内存中只存贮一个简单的数字即可,然后根据【flags】标记来解析。 19 Console.WriteLine("{0}|{1}|{2}={3}", FileAttributes.Hidden, FileAttributes.ReadOnly,FileAttributes.System,(int)file.Attributes); 20 21 if ((file.Attributes & System.IO.FileAttributes.Hidden) != System.IO.FileAttributes.Hidden) 22 { 23 throw new Exception("File is not hiden~"); 24 } 25 if ((file.Attributes & System.IO.FileAttributes.ReadOnly) != System.IO.FileAttributes.ReadOnly) 26 { 27 throw new Exception("File is not read-only~"); 28 } 29 30 bool result = System.Enum.IsDefined(typeof(FileAttributes), FileAttributes.Hidden); 31 Console.WriteLine("判定一个枚举值是否在一个特定的枚举类型中的特例:{0}", result); 32 33 34 Console.WriteLine("为常用组合定义枚举值:{0}", (int)DistributedChannel.FaultTolerant); 35 36 Console.WriteLine("'{0}' output as '{1}'", file.Attributes.ToString().Replace(",", "|"), file.Attributes); 37 38 FileAttributes attributes = (FileAttributes)Enum.Parse(typeof(FileAttributes), file.Attributes.ToString()); 39 Console.WriteLine(attributes); 40 } 41 } 42 }