Csharp/CSharp Tutorial/File Directory Stream/Directory

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

All Directories traverses all sub-directories under the root

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.rupression;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
public class MainClass
{
    public static void Main()
    {
        DirectoryInfo root = new DirectoryInfo(@"C:\Program Files\");
        DirectoryInfo[] dirs = root.GetDirectories("*", SearchOption.TopDirectoryOnly);
        Console.WriteLine("{0} subdirectories:", root.FullName);
        foreach (DirectoryInfo subDir in dirs)
        {
            Console.WriteLine("    {0}", subDir.Name);
        }
    }
}
C:\Program Files\ subdirectories:
    Adobe
    AMD
    ATI Technologies
    Common Files
    ComPlus Applications
    CONEXANT

Changing current directory to c:\\

using System;
using System.IO;
static class MainClass
{
    static void Main()
    {
       Directory.SetCurrentDirectory(@"c:\");
    }
}

Create directory structure

using System;
using System.IO.IsolatedStorage;
using System.IO;
  class MainClass
  {
    static void Main(string[] args)
    {
      using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
      {
        store.CreateDirectory(@"MyDir\XmlData");
        store.CreateDirectory("MyDir\\BinaryData");
        store.CreateDirectory("MyDir/TextData");
      }
    }
  }

Creating Subdirectory and Manipulating File

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
    class Tester
    {
        public static void Main()
        {
            ExploreDirectory(new DirectoryInfo("c:\\"));
        }
        private static void ExploreDirectory(DirectoryInfo dir)
        {
            string newDirectory = "newTest";
            DirectoryInfo newSubDir = dir.CreateSubdirectory(newDirectory);
            FileInfo[] filesInDir = dir.GetFiles();
            foreach (FileInfo file in filesInDir)
            {
                string fullName = newSubDir.FullName +"\\" + file.Name;
                file.CopyTo(fullName);
                Console.WriteLine(file.FullName);
            }
            filesInDir = newSubDir.GetFiles();
            int counter = 0;
            foreach (FileInfo file in filesInDir)
            {
                string fullName = file.FullName;
                file.MoveTo(fullName + ".bak");
                Console.WriteLine("{0} renamed to {1}",fullName, file.FullName);
            }
            newSubDir.Delete(true); 
        }
    }

Delete Directory

using System;
using System.IO;
class MaionClass
{
  public static void Main(String[] args)
  {
    try
    {
      Directory.Delete(@"C:\WinNT\MyFoo");
      Directory.Delete(@"C:\WinNT\MyBar", true);
    }
    catch(IOException e)
    {
      Console.WriteLine(e.Message);
    }
  }
}

Directory Attributes

using System;
using System.IO;
class MainClass
{
  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() 
  {
    DirectoryInfo di = new DirectoryInfo("c:\\");
    
    FileAttributes f = di.Attributes;
    Console.WriteLine("Directory c:\\ has attributes:");
    DecipherAttributes(f);
  }
}
Directory c:\ has attributes:
Directory
Hidden
System

Directory.Exists

using System;
using System.IO;
static class MainClass
{
    static void Main(string[] args)
    {
        Console.WriteLine(Directory.Exists("c:\\"));
    }
}
True

DirectoryInfo: creation time, last write time, last access time

using System;
using System.IO;
class MainClass
{
    public static void Main(string[] args)
    {
        FileInfo file = new FileInfo("c:\\test.txt");    
        // Display directory information.
        DirectoryInfo dir = file.Directory;
        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());
        }
    
    }
}
Directory created: 27/08/2006 3:07:02 PM
Directory last updated: 25/03/2007 2:04:08 PM
Directory last accessed: 25/03/2007 2:11:11 PM

DirectoryInfo: Directory attribute list and Directory contains

using System;
using System.IO;
class MainClass
{
    public static void Main(string[] args)
    {
        FileInfo file = new FileInfo("c:\\test.txt");
        // Display directory information.
        DirectoryInfo dir = file.Directory;
        if (dir.Exists)
        {
            Console.Write("Directory attribute list: ");
            Console.WriteLine(dir.Attributes.ToString());
            Console.WriteLine("Directory contains: " + dir.GetFiles().Length.ToString() + " files");
        }
    }
}
Directory attribute list: Hidden, System, Directory
Directory contains: 12 files

Exploring Files And Sub directories

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
   class Tester
   {
      static int dirCounter = 1;
      static int fileCounter = 0;
      public static void Main()
      {
         ExploreDirectory( new DirectoryInfo( "c:\\") );
      }
      static void ExploreDirectory( DirectoryInfo dir )
      {
         FileInfo[] filesInDir = dir.GetFiles();
         foreach ( FileInfo file in filesInDir )
         {
            Console.WriteLine( "{0} [{1}] Size: {2} bytes",
               file.Name,
               file.LastWriteTime,
               file.Length );
            fileCounter++;
         }
         DirectoryInfo[] directories = dir.GetDirectories();
         foreach ( DirectoryInfo newDir in directories )
         {
            dirCounter++;  // increment the counter
            ExploreDirectory( newDir );
         }
      }
   }

Get Current Directory

using System;
using System.IO;
static class MainClass
{
    static void Main()
    {
        Console.WriteLine("Using: " + Directory.GetCurrentDirectory());
    }
}
Using: C:\Java_Dev\WEB\dev\CSharp

Get DirectoryInfo from FileInfo: name, parent directory name, directory exists

using System;
using System.IO;
class MainClass
{
    public static void Main(string[] args)
    {
        FileInfo file = new FileInfo("c:\\test.txt");
        // Display directory information.
        DirectoryInfo dir = file.Directory;
        Console.WriteLine("Checking directory: " + dir.Name);
        Console.WriteLine("In directory: " + dir.Parent.Name);
        Console.Write("Directory exists: ");
        Console.WriteLine(dir.Exists.ToString());
    }
}
Checking directory: c:\
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an ob
ject.
   at MainClass.Main(String[] args)

Get relative path

using System;
using System.IO;
static class MainClass
{
    static void Main()
    {
        Console.WriteLine("The relative path "file.txt" " + Path.GetFullPath("file.txt"));
    }
}
c:\file.txt

Get the files from the root directory

using System;
using System.IO;
class MainClass
{
  public static void Main() 
  {
    string[] aFiles = Directory.GetFiles("c:\\");
    foreach (string s in aFiles)
      Console.WriteLine(s);
  }
}
c:\AUTOEXEC.BAT
c:\boot.ini
c:\CONFIG.SYS
c:\hiberfil.sys
c:\initest.ini
c:\IO.SYS
c:\MSDOS.SYS
c:\myfile.txt
c:\NTDETECT.ru
c:\ntldr
c:\pagefile.sys
c:\records.bin
c:\Test.txt
c:\test.xml
c:\Testing.txt
c:\xmlWriterTest.xml

List directory under a directory

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    DirectoryInfo MyRoot = new DirectoryInfo(@"c:\projects");
    DirectoryInfo[] MySub = MyRoot.GetDirectories();
    foreach (DirectoryInfo D in MySub)
    {
      Console.WriteLine(D.Name);
    }
  }
}

List files under a directory

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    DirectoryInfo MyRoot = new DirectoryInfo(@"c:\projects");
    FileInfo[] MyFiles = MyRoot.GetFiles();
    foreach (FileInfo F in MyFiles)
    {
      Console.WriteLine(F.Name);
    }
  }
}
Testing.txt

Modify directory structure

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;

  class Program
  {
    static void Main(string[] args)
    {
      DirectoryInfo dir = new DirectoryInfo(".");
      // Create \MyFolder off initial directory.
      dir.CreateSubdirectory("MyFolder");
      // Capture returned DirectoryInfo object.
      DirectoryInfo myDataFolder = dir.CreateSubdirectory(@"MyFolder2\Data");
      // Prints path to ..\MyFolder2\Data.
      Console.WriteLine("New Folder is: {0}", myDataFolder);
    }
  }

Recursely Explore Directories

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
    class Tester
    {
        public static void Main()
        {
            ExploreDirectory(new DirectoryInfo("c:\\"));
        }
        private static void ExploreDirectory(DirectoryInfo dir)
        {
            Console.WriteLine("[{0}] {1} \n",dir.Name, dir.LastAccessTime);
            DirectoryInfo[] directories = dir.GetDirectories();
            foreach (DirectoryInfo newDir in directories)
            {
                ExploreDirectory(newDir);
            }
        }
    }

Recursive Directory use

using System;
using System.IO;
class MainClass
{
  public static void ShowDirectory(DirectoryInfo di, int intLevel) 
  {
    string strPad = new String(" ", 2*intLevel);
    Console.WriteLine(strPad + di.Name);
    foreach (DirectoryInfo diChild in di.GetDirectories())
      ShowDirectory(diChild, intLevel+1);
  }
  public static void Main() 
  {
    DirectoryInfo di = new DirectoryInfo("c:\\");
    ShowDirectory(di, 0);
  }
}
c:\
  b
  Documents and Settings
    All Users
      Application Data
        Adobe
          Acrobat
            6.0
              Replicate
                Security
        Microsoft
          CoreCon
^CTerminate batch job (Y/N)? n

Show basic directory info

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;

  class Program
  {
    static void Main(string[] args)
    {
      DirectoryInfo dir = new DirectoryInfo(@"C:\Windows");
      // Dump directory information.
      Console.WriteLine("***** Directory Info *****");
      Console.WriteLine("FullName: {0}", dir.FullName);
      Console.WriteLine("Name: {0}", dir.Name);
      Console.WriteLine("Parent: {0}", dir.Parent);
      Console.WriteLine("Creation: {0}", dir.CreationTime);
      Console.WriteLine("Attributes: {0}", dir.Attributes);
      Console.WriteLine("Root: {0}", dir.Root);
    }
  }

Traverse all files under the root

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.IO.rupression;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
public class MainClass
{
    public static void Main()
    {
        DirectoryInfo root = new DirectoryInfo(@"C:\Program Files\");
        DirectoryInfo[] dirs = root.GetDirectories("*", SearchOption.TopDirectoryOnly);
        Console.WriteLine("{0} subdirectories:", root.FullName);
        FileInfo[] files = root.GetFiles();
        Console.WriteLine("files:");
        foreach (FileInfo file in files)
        {
            Console.WriteLine("    {0} ({1} bytes)", file.Name, file.Length);
        }
    }
}
C:\Program Files\ subdirectories:
files:

Use DirectoryInfo to create sub directory

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    DirectoryInfo MyRoot = new DirectoryInfo(@"c:\projects");
        MyRoot.CreateSubdirectory("MyFolder");
  }
}

Use file filer on a directory

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

Using Directory type

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;

  class Program
  {
    static void Main(string[] args)
    {
      string[] drives = Directory.GetLogicalDrives();
      foreach (string s in drives)
        Console.WriteLine("--> {0} ", s);
      try
      {
        Directory.Delete(string.Format(@"{0}\MyFolder", Environment.CurrentDirectory));
        Directory.Delete(string.Format(@"{0}\MyFolder2", Environment.CurrentDirectory), true);
      }
      catch (IOException e)
      {
        Console.WriteLine(e.Message);
      }
    }
  }