Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 4
System.IO
File Class
File Methods
 SetAttributes Method
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2010/.NET Framework 4

Other versions are also available for the following:
.NET Framework Class Library
File..::.SetAttributes Method

Updated: October 2010

Sets the specified FileAttributes of the file on the specified path.

Namespace:  System.IO
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic
Public Shared Sub SetAttributes ( _
    path As String, _
    fileAttributes As FileAttributes _
)
C#
public static void SetAttributes(
    string path,
    FileAttributes fileAttributes
)
Visual C++
public:
static void SetAttributes(
    String^ path, 
    FileAttributes fileAttributes
)
F#
static member SetAttributes : 
        path:string * 
        fileAttributes:FileAttributes -> unit 

Parameters

path
Type: System..::.String
The path to the file.
fileAttributes
Type: System.IO..::.FileAttributes
A bitwise combination of the enumeration values.
ExceptionCondition
ArgumentException

path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid.

PathTooLongException

The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

NotSupportedException

path is in an invalid format.

DirectoryNotFoundException

The specified path is invalid, (for example, it is on an unmapped drive).

FileNotFoundException

The file cannot be found.

UnauthorizedAccessException

path specified a file that is read-only.

-or-

This operation is not supported on the current platform.

-or-

path specified a directory.

-or-

The caller does not have the required permission.

The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see GetCurrentDirectory.

Certain file attributes, such as Hidden and ReadOnly, can be combined. Other attributes, such as Normal, must be used alone.

It is not possible to change the compression status of a File object using the SetAttributes method.

For a list of common I/O tasks, see Common I/O Tasks.

The following example demonstrates the GetAttributes and SetAttributes methods by applying the Archive and Hidden attributes to a file.

Visual Basic
Imports System
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 exists.
        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
C#
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.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;
    }
}
Visual C++
using namespace System;
using namespace System::IO;
using namespace System::Text;
int main()
{
   String^ path = "c:\\temp\\MyTest.txt";

   // Create the file if it exists.
   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 );
   }
}

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
  • FileIOPermission 

    for reading and writing files. Associated enumeration: FileIOPermissionAccess..::.Write

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Date

History

Reason

October 2010

Changed example to correctly remove attributes.

Customer feedback.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Set compression status of a File object      Evgeny Balykov   |   Edit   |   Show History

You can use DeviceIoControl interop:

internal static class NativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DeviceIoControl(
SafeFileHandle hDevice,
int dwIoControlCode,
ref short lpInBuffer,
int nInBufferSize,
IntPtr lpOutBuffer,
int nOutBufferSize,
ref int lpBytesReturned,
IntPtr lpOverlapped);
}

public class SomeClass {

public static void SetCompressionAttribute(string output)
{
using (FileStream outputStream = File.Create(output))
{
// Write to file

// Setting compression flag
const int SetCompressionCode = 0x9C040;
const short CompressionFormatDefault = 1;
int bytesReturned = 0;
short inputBuffer = CompressionFormatDefault;

int result = NativeMethods.DeviceIoControl(
outputStream.SafeFileHandle,
SetCompressionCode,
ref inputBuffer,
sizeof(short),
IntPtr.Zero,
0,
ref bytesReturned,
IntPtr.Zero);

if (result == 0)
{
Marshal.ThrowExceptionForHR(Marshal.GetLastWin32Error());
}
}
}
}

Tags What's this?: Add a tag
Flag as ContentBug
Misleading info in Exceptions      cunningdave   |   Edit   |   Show History
Note that the guidelines in UnauthorizedAccessException are misleading - it seems to suggest that if a file is read-only, that you cannot change its attributes. This is not correct; in fact, this is expected if you are trying to delete a read-only file. You need to first change the attribs to Normal, then delete it. $0$0 $0 $0Also, there's a typo in the example:$0 $0$0 $0 $0 $0// Create the file if it doesn't exist$0 $0
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker