Csharp/C Sharp/File Stream/File — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 15:31, 26 мая 2010

Delete a file

using System;
using System.IO;
class MainClass {
    static void Main() {
        string tempFile = Path.GetTempFileName();
        Console.WriteLine("Using " + tempFile);
        using (FileStream fs = new FileStream(tempFile, FileMode.Open)) {
            // (Write some data.)
        }
        // Now delete the file.
        File.Delete(tempFile);
    }
}


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] & (char) 0xdf);
                if (ch != "Y")
                    return;
                bOverwrite = true;
            }
            File.Copy (args[0], args[1], bOverwrite);
        }
    }
}


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);
    }
}


Get file Creation Time

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
 /*
  Example15_3.cs illustrates the File class
*/
using System;
using System.Windows.Forms;
using System.IO;
public class Example15_3 
{
    [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
      string s = dlgOpen.FileName;
      Console.WriteLine("Filename " + s);
      Console.WriteLine(" Created at " + File.GetCreationTime(s));
      Console.WriteLine(" Accessed at " + 
       File.GetLastAccessTime(s));
    }
  }
}


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 & FileAttributes.Archive) == FileAttributes.Archive)
      Console.WriteLine("Archive");
    if ((f & FileAttributes.rupressed) == FileAttributes.rupressed)
      Console.WriteLine("Compressed");
    if ((f & FileAttributes.Device) == FileAttributes.Device)
      Console.WriteLine("Device");
    if ((f & FileAttributes.Directory)   == FileAttributes.Directory)
      Console.WriteLine("Directory");
    if ((f & FileAttributes.Encrypted)  == FileAttributes.Encrypted)
      Console.WriteLine("Encrypted");
    if ((f & FileAttributes.Hidden)  == FileAttributes.Hidden)
      Console.WriteLine("Hidden");
    if ((f & FileAttributes.NotContentIndexed)  == FileAttributes.NotContentIndexed)
      Console.WriteLine("NotContentIndexed");
    if ((f & FileAttributes.Offline)  == FileAttributes.Offline)
      Console.WriteLine("Offline");
    if ((f & FileAttributes.ReadOnly)  == FileAttributes.ReadOnly)
      Console.WriteLine("ReadOnly");
    if ((f & FileAttributes.ReparsePoint)  == FileAttributes.ReparsePoint)
      Console.WriteLine("ReparsePoint");
    if ((f & FileAttributes.SparseFile)  == FileAttributes.SparseFile)
      Console.WriteLine("SparseFile");
    if ((f & FileAttributes.System)  == FileAttributes.System)
      Console.WriteLine("System");
    if ((f & 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);
    }
  }
}


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 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();
  }
}


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 ("\tCreated on " + str.Substring (0, index) + " at " + str.Substring (index + 1));
            str = accessed.ToString();
            index = str.IndexOf (" ");
            Console.WriteLine ("\tLast accessed on " + str.Substring (0, index) + " at " + str.Substring (index + 1));
            str = written.ToString();
            index = str.IndexOf (" ");
            Console.WriteLine ("\tLast 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 ();
        }
    }
}