SetFileAttributes (kernel32)
Last changed: -129.94.142.244

.
Summary

C# Signature:

[DllImport("kernel32.dll")]
static extern bool SetFileAttributes(string lpFileName, uint dwFileAttributes);

Alternative C# Signature:

[DllImport("kernel32.dll")]
static extern bool SetFileAttributes(
     string lpFileName,
     [MarshalAs(UnmanagedType.U4)] FileAttributes dwFileAttributes);

User-Defined Types:

None.

You can create this FileAttributes type to go in your class and be used with the alternative signature if you wish (or you can use the System.IO.FileAttributes as displayed in the below example):

[Flags] public enum FileAttributes : uint
{
    Readonly = 0x00000001,
    Hidden = 0x00000002,
    System = 0x00000004,
    Directory = 0x00000010,
    Archive = 0x00000020,
    Device = 0x00000040,
    Normal = 0x00000080,
    Temporary = 0x00000100,
    SparseFile = 0x00000200,
    ReparsePoint = 0x00000400,
    Compressed = 0x00000800,
    Offline = 0x00001000,
    NotContentIndexed = 0x00002000,
    Encrypted = 0x00004000,
    Write_Through = 0x80000000,
    Overlapped = 0x40000000,
    NoBuffering = 0x20000000,
    RandomAccess = 0x10000000,
    SequentialScan = 0x08000000,
    DeleteOnClose = 0x04000000,
    BackupSemantics = 0x02000000,
    PosixSemantics = 0x01000000,
    OpenReparsePoint = 0x00200000,
    OpenNoRecall = 0x00100000,
    FirstPipeInstance = 0x00080000
}

Notes:

This method works for Alternate Data Streams, also great when used with the Unicode header \\?\ to change the attributes of files who have paths to long to be dealt with via the shell.

Tips & Tricks:

Please add some!

Sample Code:

Using the "alternative" method above you can make calls like so:

SetFileAttributes("pathname", FileAttributes.System | FileAttributes.Hidden | FileAttributes.Archive);

Alternative Managed API:

System.IO.File.SetAttributes(String path, System.IO.FileAttributes fileAttributes);

Documentation