Sponsored Ad

Thursday, December 16, 2010

How to Set File Attribute using C#

Are you new to input/output operation in C#. This example will help you to set file attributes in C#. There are four file attributes available with file

1. Hidden
2. Archive
3. System
4. ReadOnly

By using following code you can change the attributes of any file.

How to Set File Attribute using C#

C# Code to Change File Attributes:

using System;
using System.IO;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string file_location = @"c:\myfile.txt";

            //set normal file
            File.SetAttributes(file_location, FileAttributes.Normal);

            bool bReadOnly = ((File.GetAttributes(file_location) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
            Console.WriteLine("ReadOnly Attribute: " + bReadOnly.ToString());

            // set archive and read only attributes
            File.SetAttributes(file_location, FileAttributes.Archive |
                                         FileAttributes.ReadOnly);

            bReadOnly = ((File.GetAttributes(file_location) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
            Console.WriteLine("ReadOnly Attribute: " + bReadOnly.ToString());

            bool bArchive = ((File.GetAttributes(file_location) & FileAttributes.Archive) == FileAttributes.Archive);
            Console.WriteLine("Archive Attribute: " + bArchive.ToString());

            Console.ReadLine();
        }

    }
}

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers