martedì 25 novembre 2008

File attributes with C#

The class I've posted shows how to use the fiel attributes with c#.
To get file attributes (in .Net) you need more steps, with this class you have immediatly all you need.
I covered the 4 standard attribute but you can extend the class with other attributes. The file is .called FileAttributeEx.cs and this it the code.

using
System;
using System.IO;

namespace FileAttributeEx
{
class FileAttributesEx
{
private string filepath = string.Empty;

public string FilePath
{
get { return filepath; }
set { filepath = value;}
}

public FileAttributesEx() { }
public FileAttributesEx(string path)
{
FilePath = path;
}

public bool isReadOnly ()
{
return (File.GetAttributes(FilePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
}

public bool isHidden()
{
return (File.GetAttributes(FilePath) & FileAttributes.Hidden) == FileAttributes.Hidden;
}

public bool isArchive()
{
return (
File.GetAttributes(FilePath) & FileAttributes.Archive) == FileAttributes.Archive;
}

public bool isSystem()
{
return (File.GetAttributes(FilePath) & FileAttributes.System) == FileAttributes.System;
}

public void AddSystem()
{
File.SetAttributes(FilePath, File.GetAttributes(FilePath) | FileAttributes.System);
}

public void AddReadOnly()
{
File.SetAttributes(FilePath, File.GetAttributes(FilePath) | FileAttributes.ReadOnly);
}

public void AddHidden()
{
File.SetAttributes(FilePath, File.GetAttributes(FilePath) | FileAttributes.Hidden);
}

public void AddArchive()
{
File.SetAttributes(FilePath, File.GetAttributes(FilePath) | FileAttributes.Archive);
}

public void Clear()
{
File.SetAttributes(filepath, File.GetAttributes(filepath)
& ~(FileAttributes.Archive |
FileAttributes.ReadOnly| FileAttributes.System|FileAttributes.Hidden));
}
}
}

To use it in your project simply, add the file to your project, add a new instance of it and call the metods you need.
Here a sample:

FileAttributesEx fileAttr = new FileAttributesEx(sFileName);

if (fileAttr.isArchive())
//Do something
if (fileAttr.isHidden())
//Do something

fileAttr.Clear();

fileAttr.AddReadOnly();

Have fun.

Nessun commento: