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

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

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

Calculate Directory Size

 
using System;
using System.IO;
class MainClass {
    static void Main(string[] args) {
        DirectoryInfo dir = new DirectoryInfo("c:\\");
        Console.WriteLine("Total size: " + CalculateDirectorySize(dir, true).ToString() + " bytes.");
    }
    static long CalculateDirectorySize(DirectoryInfo directory, bool includeSubdirectories) {
        long totalSize = 0;
        FileInfo[] files = directory.GetFiles();
        foreach (FileInfo file in files) {
            totalSize += file.Length;
        }
        if (includeSubdirectories) {
            DirectoryInfo[] dirs = directory.GetDirectories();
            foreach (DirectoryInfo dir in dirs) {
                totalSize += CalculateDirectorySize(dir, true);
            }
        }
        return totalSize;
    }
}


Changes the current working directory and then lists the files in the directory

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//  ShowDir.cs -- Changes the current working directory and then lists
//                the files in the directory.
//
//                Compile this program with the following command line:
//                    C:>csc ShowDir.cs
using System;
using System.IO;
namespace nsStreams
{
    public class ShowDir
    {
        static public void Main (string [] args)
        {
            if (args.Length > 0)
            {
// Build the directory name from the arguments (a directory name may
// contain spaces).
                string DirName = "";
                foreach (string str in args)
                {
                    DirName += str;
                    DirName += " ";
                }
// Strip any leading or trailing spaces from the directory name
                DirName = DirName.Trim ();
// Check whether the directory exists
//                if (!Directory.Exists(DirName))
//                {
//                    Console.WriteLine ("No such directory: " + DirName);
//                    return;
//                }
// Set the current working directory
                try
                {
                    Directory.SetCurrentDirectory (DirName);
                }
                catch (UnauthorizedAccessException)
                {
                    Console.WriteLine ("Not authorized to access " + DirName);
                    return;
                }
                catch (FileNotFoundException)
                {
                    Console.WriteLine ("No such directory: " + DirName);
                    return;
                }
            }
// List the files in the selected directory
            string [] files = Directory.GetFiles (".");
            foreach (string str in files)
            {
                int index = str.LastIndexOf ("\\");
                Console.WriteLine (str.Substring (index + 1));
            }
        }
    }
}


Check the Existance of a Directory

using System;
using System.IO;
class MainClass {
    static void Main(string[] args) {
        foreach (string arg in args) {
            Console.Write(arg);
            if (Directory.Exists(arg)) {
                Console.WriteLine(" is a  directory");
            } else if (File.Exists(arg)) {
                Console.WriteLine(" is a  file");
            } else {
                Console.WriteLine(" does not exist");
            }
        }
    }
}


Copy Directory

 
using System;
using System.IO;
class MainClass {
    static void Main(string[] args) {
        DirectoryInfo sourceDir = new DirectoryInfo("c:\\source");
        DirectoryInfo destinationDir = new DirectoryInfo("c:\\target");
        CopyDirectory(sourceDir, destinationDir);
    }
    static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination) {
        if (!destination.Exists) {
            destination.Create();
        }
        // Copy all files.
        FileInfo[] files = source.GetFiles();
        foreach (FileInfo file in files) {
            file.CopyTo(Path.rubine(destination.FullName,
               file.Name));
        }
        // Process subdirectories.
        DirectoryInfo[] dirs = source.GetDirectories();
        foreach (DirectoryInfo dir in dirs) {
            string destinationDir = Path.rubine(destination.FullName, dir.Name);
            CopyDirectory(dir, new DirectoryInfo(destinationDir));
        }
    }
}


Directory Counter

 
using System;
using System.IO;
public class DirectoryCounter {
    public static void Main() {
        DirectoryInfo myDir = new DirectoryInfo(@"c:\Program Files");
        int total = CountDirectories(myDir);
        Console.WriteLine(total);
    }
    public static int CountDirectories(DirectoryInfo dir) {
        DirectoryInfo[] dirs = dir.GetDirectories();
        int count = dirs.Length;
        foreach (DirectoryInfo subDir in dirs) {
            count += CountDirectories(subDir);
        }
        return count;
    }
}


Directory Object

/*
 * C# Programmers Pocket Consultant
 * Author: Gregory S. MacBeth
 * Email: gmacbeth@comporium.net
 * Create Date: June 27, 2003
 * Last Modified Date:
 * Version: 1
 */
using System;
using System.IO;
namespace Client.Chapter_11___File_and_Streams
{
  public class DirectoryObject {
    static void Main(string[] args)
    {
      DirectoryInfo MyRoot = new DirectoryInfo(@"c:\projects");
      DirectoryInfo[] MySub;
      DirectoryInfo TheFolder = null;
      FileInfo[] MyFiles;
      FileInfo TheFile = null;
      FileStream MyStream;
      MyRoot.CreateSubdirectory("MyFolder");
      MySub = MyRoot.GetDirectories();
      foreach (DirectoryInfo D in MySub)
      {
        if (D.Name == "MyFolder")
          TheFolder = D;
      }
      MyFiles = TheFolder.GetFiles();
      foreach (FileInfo F in MyFiles)
      {
        if (F.Name == "Testing.txt")
        {
          TheFile = F;
          MyStream = TheFile.Open(FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
          int i = 0;
          byte b = 0;
          while (i != 000)
          {
            MyStream.WriteByte(b);
            i++;
            b++;
          }
        }
      }
      TheFile.Delete();
      TheFolder.Delete();
    }
  }
}


Directory Tree Host

/*
User Interfaces in C#: Windows Forms and Custom Controls
by Matthew MacDonald
Publisher: Apress
ISBN: 1590590457
*/
using System.IO;
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
namespace DirectoryTreeHost
{
    /// <summary>
    /// Summary description for DirectoryTreeHost.
    /// </summary>
    public class DirectoryTreeHost : System.Windows.Forms.Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ruponentModel.Container components = null;
        public DirectoryTreeHost()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }
        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            // 
            // DirectoryTreeHost
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Name = "DirectoryTreeHost";
            this.Text = "DirectoryTreeHost";
            this.Load += new System.EventHandler(this.DirectoryTreeHost_Load);
        }
        #endregion
        private void DirectoryTreeHost_Load(object sender, System.EventArgs e)
        {
            DirectoryTree dirTree = new 
                DirectoryTree();
            dirTree.Size = new Size(this.Width - 30, this.Height - 60);
            dirTree.Location = new Point(5, 5);
            dirTree.Drive = Char.Parse("C");
            this.Controls.Add(dirTree);
        }
        public static void Main()
        {
            Application.Run(new DirectoryTreeHost());
        }
    }
    public class DirectoryTree : TreeView
    {
        public delegate void DirectorySelectedDelegate(object sender,
            DirectorySelectedEventArgs e);
        public event DirectorySelectedDelegate DirectorySelected;
        
        private Char drive;
        public Char Drive
        {
            get
            {
                return drive;
            }
            set
            {
                drive = value;
                RefreshDisplay();
            }
        }
        
        // This is public so a Refresh can be triggered manually.
        public void RefreshDisplay()
        {
            // Erase the existing tree.
            this.Nodes.Clear();
            
            // Set the first node.
            TreeNode rootNode = new TreeNode(drive + ":\\");
            this.Nodes.Add(rootNode);
            
            // Fill the first level and expand it.
            Fill(rootNode);
            this.Nodes[0].Expand();
        }
        
        private void Fill(TreeNode dirNode)
        {
            DirectoryInfo dir = new DirectoryInfo(dirNode.FullPath);
            
            // An exception could be thrown in this code if you don"t
            // have sufficient security permissions for a file or directory.
            // You can catch and then ignore this exception.
            
            foreach (DirectoryInfo dirItem in dir.GetDirectories())
            {
                // Add node for the directory.
                TreeNode newNode = new TreeNode(dirItem.Name);
                dirNode.Nodes.Add(newNode);
                newNode.Nodes.Add("*");
            }
        }
        
        protected override void OnBeforeExpand(TreeViewCancelEventArgs e)
        {
            base.OnBeforeExpand(e);
            // If a dummy node is found, remove it and read the real directory list.
            if (e.Node.Nodes[0].Text == "*")
            {
                e.Node.Nodes.Clear();
                Fill(e.Node);
            }
        }
        
        protected override void OnAfterSelect(TreeViewEventArgs e)
        {
            base.OnAfterSelect(e);
            
            // Raise the DirectorySelected event.
            if (DirectorySelected != null)
            {
                DirectorySelected(this,
                    new DirectorySelectedEventArgs(e.Node.FullPath));
            }
        }
    }
    public class DirectorySelectedEventArgs : EventArgs
    {
        public string DirectoryName;
        public DirectorySelectedEventArgs(string directoryName)
        {
            this.DirectoryName = directoryName;
        }
    }

}


File Search

 
using System;
using System.IO;
public class FileSearch {
    public static void Main() {
        String searchName = "win";
        DirectoryInfo myDir = new DirectoryInfo(@"c:\Program Files");
        SearchDirectories(myDir, searchName);
    }
    public static void SearchDirectories(DirectoryInfo dir, String target) {
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files) {
            if (file.Name.IndexOf(target) > -1) {
                Console.WriteLine(file.Name);
            }
        }
        DirectoryInfo[] dirs = dir.GetDirectories();
        foreach (DirectoryInfo subDir in dirs) {
            SearchDirectories(subDir, target);
        }
    }
}


Find Files That Match a Wildcard Expression

 
using System;
using System.IO;
public class WildcardTest {
    private static void Main(string[] args) {
        DirectoryInfo dir = new DirectoryInfo("c:\\");
        FileInfo[] files = dir.GetFiles("*");
            
        foreach (FileInfo file in files) {
            Console.Write("Name: " + file.Name + "  ");
            Console.WriteLine("Size: " + file.Length.ToString());
        }
    }
}


Get Creation Time

 
using System;
using System.IO;
class MainClass {
    static void Main(string[] args) {
        FileInfo file = new FileInfo("c:\\a.txt");
        // Display directory information.
        DirectoryInfo dir = file.Directory;
        Console.WriteLine("Checking directory: " + dir.Name);
        Console.WriteLine("In directory: " + dir.Name);
        Console.Write("Directory exists: ");
        Console.WriteLine(dir.Exists.ToString());
        if (dir.Exists) {
            Console.Write("Directory created: ");
            Console.WriteLine(dir.CreationTime.ToString());
        }
        Console.WriteLine();
    }
}


Get Current Directory

using System;
using System.IO;
class MainClass {
    static void Main() {
        Console.WriteLine("Using: " + Directory.GetCurrentDirectory());
        Console.WriteLine("The relative path "file.txt" " + "will automatically become: "" + Path.GetFullPath("file.txt") + """);
    }
}


Get directory name and file information in that directory

 
using System;
using System.IO;
public class DirInfoApp
{
    public static void Main(string[] args)
    {
        DirectoryInfo dir = new DirectoryInfo(Directory.GetCurrentDirectory());
        Console.WriteLine("Current Dir: {0}", dir.FullName);
   
        foreach (FileInfo f in dir.GetFiles())
        {
            Console.WriteLine("{0,-14}{1,10}{2,20}",f.Name, f.Length, f.LastWriteTime);
        }
    }
}


Get Directory properties from DirectionInfo class

 
using System;
using System.IO;
class MainClass {
    static void Main(string[] args) {
        FileInfo file = new FileInfo("c:\\a.txt");
        // Display directory information.
        DirectoryInfo dir = file.Directory;
        Console.WriteLine("Checking directory: " + dir.Name);
        Console.WriteLine("In directory: " + dir.Name);
        Console.Write("Directory exists: ");
        Console.WriteLine(dir.Exists.ToString());
        if (dir.Exists) {
            Console.Write("Directory attribute list: ");
            Console.WriteLine(dir.Attributes.ToString());
        }
        Console.WriteLine();
    }
}


Get Files from a directory

 

using System;
using System.IO;
class MainClass {
    static void Main(string[] args) {
        DirectoryInfo dir = new DirectoryInfo("c:\\");
        FileInfo[] files = dir.GetFiles("c:\\a.txt");
        foreach (FileInfo file in files) {
            Console.Write("Name: " + file.Name + "  ");
            Console.WriteLine("Size: " + file.Length.ToString());
        }
    }
}


Get Last Access Time

 
using System;
using System.IO;
class MainClass {
    static void Main(string[] args) {
        FileInfo file = new FileInfo("c:\\a.txt");
        // Display directory information.
        DirectoryInfo dir = file.Directory;
        Console.WriteLine("Checking directory: " + dir.Name);
        Console.WriteLine("In directory: " + dir.Name);
        Console.Write("Directory exists: ");
        Console.WriteLine(dir.Exists.ToString());
        if (dir.Exists) {
            Console.Write("Directory last accessed: ");
            Console.WriteLine(dir.LastAccessTime.ToString());
        }
        Console.WriteLine();
    }
}


Get Last Write Time

 
using System;
using System.IO;
class MainClass {
    static void Main(string[] args) {
        FileInfo file = new FileInfo("c:\\a.txt");
        // Display directory information.
        DirectoryInfo dir = file.Directory;
        Console.WriteLine("Checking directory: " + dir.Name);
        Console.WriteLine("In directory: " + dir.Name);
        Console.Write("Directory exists: ");
        Console.WriteLine(dir.Exists.ToString());
        if (dir.Exists) {
            Console.Write("Directory last updated: ");
            Console.WriteLine(dir.LastWriteTime.ToString());
        }
        Console.WriteLine();
    }
}


Get Name, Parent, Exists properties from DirectoryInfo class

 
using System;
using System.IO;
class MainClass {
    static void Main(string[] args) {
        FileInfo file = new FileInfo("c:\\a.txt");
        // Display directory information.
        DirectoryInfo dir = file.Directory;
        Console.WriteLine("Checking directory: " + dir.Name);
        Console.WriteLine("In directory: " + dir.Name);
        Console.Write("Directory exists: ");
        Console.WriteLine(dir.Exists.ToString());
        if (dir.Exists) {
            Console.Write("Directory created: ");
            Console.WriteLine(dir.CreationTime.ToString());
            Console.Write("Directory last updated: ");
            Console.WriteLine(dir.LastWriteTime.ToString());
            Console.Write("Directory last accessed: ");
            Console.WriteLine(dir.LastAccessTime.ToString());
            Console.Write("Directory attribute list: ");
            Console.WriteLine(dir.Attributes.ToString());
            Console.WriteLine("Directory contains: " +
               dir.GetFiles().Length.ToString() + " files");
        }
        Console.WriteLine();
    }
}


illustrates recursive Directory use

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
 /*
  Example15_8.cs illustrates recursive Directory use
*/
using System;
using System.IO;
public class Example15_8 
{
  // ShowDirectory prints the directory name
  // and retrieves its children
  public static void ShowDirectory(DirectoryInfo di, int intLevel) 
  {
    try
    {
      // print out the directory name, after 2*intLevel spaces
      string strPad = new String(" ", 2*intLevel);
      Console.WriteLine(strPad + di.Name);
      // get its children and recursively call this routine
      // with one more level of indenting
      foreach (DirectoryInfo diChild in di.GetDirectories())
        ShowDirectory(diChild, intLevel+1);
    } 
    catch {} // just keep going in case of any error
    finally{}
  }
  public static void Main() 
  {
    // create a DirectoryInfo object
    DirectoryInfo di = new DirectoryInfo("c:\\");
    
    // And pass it to the recursive printing routine
    ShowDirectory(di, 0);
  }
}


illustrates the Directory class

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
 /*
  Example15_7.cs illustrates the Directory class
*/
using System;
using System.IO;
public class Example15_7 
{
  // 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");
  }
  public static void Main() 
  {
    // create a DirectoryInfo object
    DirectoryInfo di = new DirectoryInfo("c:\\");
    
    // retrieve and show the directory attributes
    FileAttributes f = di.Attributes;
    Console.WriteLine("Directory c:\\ has attributes:");
    DecipherAttributes(f);
  }
}


illustrates the Directory class 2

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
 /*
  Example15_6.cs illustrates the Directory class
*/
using System;
using System.IO;
public class Example15_6 
{
  public static void Main() 
  {
    // get the files from the root directory
    string[] aFiles = Directory.GetFiles("c:\\");
    // and display them
    foreach (string s in aFiles)
      Console.WriteLine(s);
  }
}


Set Current Directory

using System;
using System.IO;
class MainClass {
    static void Main() {
        Console.WriteLine("Changing current directory to c:\\");
        Directory.SetCurrentDirectory(@"c:\");
        Console.WriteLine("Now the relative path "file.txt" " + "will automatically become "" + Path.GetFullPath("file.txt") + """);
    }
}


Traversing Directories

/*
A Programmer"s Introduction to C# (Second Edition)
by Eric Gunnerson
Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 32 - .NET Frameworks Overview\InputOutput\Traversing Directories
// copyright 2000 Eric Gunnerson
using System;
using System.IO;
class DirectoryWalker
{
    public delegate void ProcessDirCallback(DirectoryInfo dir, int level, object obj);
    public delegate void ProcessFileCallback(FileInfo file, int level, object obj);
    
    public DirectoryWalker(    ProcessDirCallback dirCallback,
    ProcessFileCallback fileCallback)
    {
        this.dirCallback = dirCallback;
        this.fileCallback = fileCallback;
    }
    
    public void Walk(string rootDir, object obj)
    {
        DoWalk(new DirectoryInfo(rootDir), 0, obj);
    }
    void DoWalk(DirectoryInfo dir, int level, object obj)
    {
        foreach (FileInfo f in dir.GetFiles())
        {
            if (fileCallback != null)
            fileCallback(f, level, obj);
        }
        foreach (DirectoryInfo d in dir.GetDirectories())
        {
            if (dirCallback != null)
            dirCallback(d, level, obj);
            DoWalk(d, level + 1, obj);
        }
    }
    
    ProcessDirCallback    dirCallback;
    ProcessFileCallback    fileCallback;
}
public class TraversingDirectories
{
    public static void PrintDir(DirectoryInfo d, int level, object obj)
    {
        WriteSpaces(level * 2);
        Console.WriteLine("Dir: {0}", d.FullName);
    }
    public static void PrintFile(FileInfo f, int level, object obj)
    {
        WriteSpaces(level * 2);
        Console.WriteLine("File: {0}", f.FullName);
    }
    public static void WriteSpaces(int spaces)
    {
        for (int i = 0; i < spaces; i++)
        Console.Write(" ");
        
    }
    public static void Main(string[] args)
    {
        DirectoryWalker dw = new DirectoryWalker(
        new DirectoryWalker.ProcessDirCallback(PrintDir),
        new DirectoryWalker.ProcessFileCallback(PrintFile));
        
        string root = ".";
        if (args.Length == 1)
        root = args[0];
        dw.Walk(root, "Passed string object");
    }
}


Uses the DirectoryInfo class to recursively show subdirectories

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

//  Dirs.cs -- Uses the DirectoryInfo class to recursively show
//             subdirectories.
//
//             Compile this program with the following command line:
//                 C:>csc Dirs.cs
using System;
using System.IO;
namespace nsStreams
{
    public class Dirs
    {
        static public void Main (string [] args)
        {
            string StartDir = "";
// Build the directory name from any arguments
            if (args.Length > 0)
            {
                foreach (string str in args)
                {
                    StartDir += str;
                    StartDir += " ";
                }
// Strip any trailing spaces from the directory name
                char [] trim = new char[1] {" "};
                StartDir.TrimEnd (trim);
            }
            else
            {
                StartDir = ".";
            }
            DirectoryInfo d;
            try
            {
                d = new DirectoryInfo (StartDir);
            }
            catch (DirectoryNotFoundException)
            {
                 Console.WriteLine ("Cannot open directory " + StartDir);
                 return;
            }
            DirectoryInfo [] dirs;
            try
            {
                dirs = d.GetDirectories ();
            }
            catch (UnauthorizedAccessException)
            {
                Console.WriteLine ("Not authorized to access " + StartDir);
                return;
            }
            catch (DirectoryNotFoundException)
            {
                 Console.WriteLine ("Cannot open directory " + StartDir);
                 return;
            }
            foreach (DirectoryInfo dir in dirs)
            {
                try
                {
                    ShowDirectories (dir, 0);
                }
                catch (UnauthorizedAccessException)
                {
                    continue;
                }
            }
        }
        static public void ShowDirectories (DirectoryInfo d, int level)
        {
            int spaces = level;
            while (spaces-- >= 0)
                Console.Write (" ");
            Console.WriteLine (d);
            DirectoryInfo [] dirs = d.GetDirectories ();
            if (dirs.Length > 0)
            {
                foreach (DirectoryInfo dir in dirs)
                {
                    try
                    {
                        ShowDirectories (dir, level + 2);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        continue;
                    }
                }
            }
        }
    }
}