Uses methods in the File class to check the status of a file

   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// Status.cs -- Uses methods in the File class to check the status of a file.
//
//              Compile this program with the following command line
//                  C:>csc Status.cs
using System;
using System.IO;

namespace nsStreams
{
    public class Status
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            if (!File.Exists (args[0]))
            {
                Console.WriteLine (args[0] + " does not exist");
                return;
            }
            DateTime created = File.GetCreationTime (args[0]);
            DateTime accessed = File.GetLastAccessTime (args[0]);
            DateTime written = File.GetLastWriteTime (args[0]);
            Console.WriteLine ("File " + args[0] + ":");
            string str = created.ToString();
            int index = str.IndexOf (" ");
            Console.WriteLine ("	Created on " + str.Substring (0, index) + " at " + str.Substring (index + 1));
            str = accessed.ToString();
            index = str.IndexOf (" ");
            Console.WriteLine ("	Last accessed on " + str.Substring (0, index) + " at " + str.Substring (index + 1));
            str = written.ToString();
            index = str.IndexOf (" ");
            Console.WriteLine ("	Last written on " + str.Substring (0, index) + " at " + str.Substring (index + 1));
        }
    }
}


           
          


Uses methods in the File class to check whether a file exists

   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// Exists.cs -- Uses methods in the File class to dheck whether a file exists.
//              If it exists, it then opens and reads the file to the console.
//
//              Compile this program with the following command line
//                  C:>csc Exists.cs
using System;
using System.IO;

namespace nsStreams
{
    public class Exists
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            if (!File.Exists (args[0]))
            {
                Console.WriteLine (args[0] + " does not exist");
                return;
            }
            StreamReader reader;
            try
            {
                reader = File.OpenText (args[0]);
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                Console.WriteLine ("Cannot open " + args[0]);
                return;
            }
            while (reader.Peek() >= 0)
            {
                Console.WriteLine (reader.ReadLine ());
            }
            reader.Close ();
        }
    }
}


           
          


File class to check whether a file exists, open and read

   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// cp.cs -- Uses methods in the File class to check whether a file exists.
//          If it exists, it then opens and reads the file to the console.
//
//          Compile this program with the following command line
//              C:>csc cp.cs
using System;
using System.IO;

namespace nsStreams
{
    public class cp
    {
        static public void Main (string [] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine ("usage: cp <copy from> <copy to>");
                return;
            }
            if (!File.Exists (args[0]))
            {
                Console.WriteLine (args[0] + " does not exist");
                return;
            }
            bool bOverwrite = false;
            if (File.Exists (args[1]))
            {
                Console.Write (args[1] + " already exists. Overwrite [Y/N]? ");
                string reply = Console.ReadLine ();
                char ch = (char) (reply[0] &amp; (char) 0xdf);
                if (ch != &#039;Y&#039;)
                    return;
                bOverwrite = true;
            }
            File.Copy (args[0], args[1], bOverwrite);
        }
    }
}



           
          


illustrates the FileSystemWatcher class


   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

 /*
  Example15_9.cs illustrates the FileSystemWatcher class
*/

using System;
using System.IO;

public class Example15_9 
{

  // event handler for file change
  public static void OnChanged(object source, FileSystemEventArgs e) 
  {
    // dump info to the screen
    Console.WriteLine("Change to " + e.FullPath + ": " +
     e.ChangeType);
  }

  public static void Main() 
  {

    // create a watcher for the c: drive
    FileSystemWatcher fsw = new FileSystemWatcher("c:");
    fsw.IncludeSubdirectories = true;

    // hook up the event handler
    fsw.Changed += new FileSystemEventHandler(OnChanged);

    // turn on file watching
    fsw.EnableRaisingEvents = true;
    
    // And wait for the user to quit
    Console.WriteLine("Press any key to exit");
    int i = Console.Read();

  }

}


           
          


illustrates the FileInfo class


   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

 /*
  Example15_5.cs illustrates the FileInfo class
*/

using System;
using System.Windows.Forms;
using System.IO;

public class Example15_5 
{
    
    [STAThread]
  public static void Main() 
  {

    // create and show an open file dialog
    OpenFileDialog dlgOpen = new OpenFileDialog();
    if (dlgOpen.ShowDialog() == DialogResult.OK)
    {
      // use the File class to return info about the file
      FileInfo fi = new FileInfo(dlgOpen.FileName);
      Console.WriteLine("Filename " + fi.FullName );
      Console.WriteLine(" Created at " + fi.CreationTime );
      Console.WriteLine(" Accessed at " + fi.LastAccessTime );
    }

  }

}


           
          


illustrates the FileAttributes enumeration


   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

 /*
  Example15_4.cs illustrates the FileAttributes enumeration
*/

using System;
using System.Windows.Forms;
using System.IO;

public class Example15_4 
{

  // the DecipherAttributes method turns file attributes
  // into something easier for people to read
  public static void DecipherAttributes(FileAttributes f) 
  {
    if ((f &amp; FileAttributes.Archive) == FileAttributes.Archive)
      Console.WriteLine("Archive");
    if ((f &amp; FileAttributes.Compressed) == FileAttributes.Compressed)
      Console.WriteLine("Compressed");
    if ((f &amp; FileAttributes.Device) == FileAttributes.Device)
      Console.WriteLine("Device");
    if ((f &amp; FileAttributes.Directory)   == FileAttributes.Directory)
      Console.WriteLine("Directory");
    if ((f &amp; FileAttributes.Encrypted)  == FileAttributes.Encrypted)
      Console.WriteLine("Encrypted");
    if ((f &amp; FileAttributes.Hidden)  == FileAttributes.Hidden)
      Console.WriteLine("Hidden");
    if ((f &amp; FileAttributes.NotContentIndexed)  == FileAttributes.NotContentIndexed)
      Console.WriteLine("NotContentIndexed");
    if ((f &amp; FileAttributes.Offline)  == FileAttributes.Offline)
      Console.WriteLine("Offline");
    if ((f &amp; FileAttributes.ReadOnly)  == FileAttributes.ReadOnly)
      Console.WriteLine("ReadOnly");
    if ((f &amp; FileAttributes.ReparsePoint)  == FileAttributes.ReparsePoint)
      Console.WriteLine("ReparsePoint");
    if ((f &amp; FileAttributes.SparseFile)  == FileAttributes.SparseFile)
      Console.WriteLine("SparseFile");
    if ((f &amp; FileAttributes.System)  == FileAttributes.System)
      Console.WriteLine("System");
    if ((f &amp; FileAttributes.Temporary)  == FileAttributes.Temporary)
      Console.WriteLine("Temporary");
  }
    
    [STAThread]
  public static void Main() 
  {

    // create and show an open file dialog
    OpenFileDialog dlgOpen = new OpenFileDialog();
    if (dlgOpen.ShowDialog() == DialogResult.OK)
    {
      // retrieve and show the file attributes
      FileAttributes f = File.GetAttributes(dlgOpen.FileName);
      Console.WriteLine("Filename " + dlgOpen.FileName +
        " has attributes:");
      DecipherAttributes(f);
    }

  }

}


           
          


Get File Access Control

   




using System;
using System.IO;
using System.Security.AccessControl;

class MainClass {
    static void Main(string[] args) {
        FileStream stream;
        string fileName;

        fileName = Path.GetRandomFileName();
        using (stream = new FileStream(fileName, FileMode.Create)) {
            // Do something.
        }
        SetRule(fileName, "Everyone", FileSystemRights.Read, AccessControlType.Deny);

        try {
            stream = new FileStream(fileName, FileMode.Create);
        } catch (Exception ex) {
            Console.WriteLine(ex.ToString());
        } finally {
            stream.Close();
            stream.Dispose();
        }
    }

    static void AddRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType) {
        FileSecurity fSecurity = File.GetAccessControl(filePath);
        fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
        File.SetAccessControl(filePath, fSecurity);
    }
    static void SetRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType) {
        FileSecurity fSecurity = File.GetAccessControl(filePath);
        fSecurity.ResetAccessRule(new FileSystemAccessRule(account, rights, controlType));
        File.SetAccessControl(filePath, fSecurity);
    }
}