Directory 类

公开用于创建、移动和枚举通过目录和子目录的静态方法。无法继承此类。

**命名空间:**System.IO
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
<ComVisibleAttribute(True)> _
Public NotInheritable Class Directory
用法
可对静态类的成员直接进行访问,无需类的实例。
[ComVisibleAttribute(true)] 
public static class Directory
[ComVisibleAttribute(true)] 
public ref class Directory abstract sealed
/** @attribute ComVisibleAttribute(true) */ 
public final class Directory
ComVisibleAttribute(true) 
public final class Directory

备注

Directory 类用于典型操作,如复制、移动、重命名、创建和删除目录。也可将 Directory 类用于获取和设置与目录的创建、访问及写入操作相关的 DateTime 信息。

由于所有的 Directory 方法都是静态的,所以如果只想执行一个操作,那么使用 Directory 方法的效率比使用相应的 DirectoryInfo 实例方法可能更高。大多数 Directory 方法要求当前操作的目录的路径。

Directory 类的静态方法对所有方法都执行安全检查。如果打算多次重用某个对象,可考虑改用 DirectoryInfo 的相应实例方法,因为并不总是需要安全检查。

提示

在接受路径作为输入字符串的成员中,路径必须是格式良好的,否则将引发异常。例如,如果路径是完全限定的但以空格开头,则路径在类的方法中不会被修剪。因此,路径的格式不是良好的,并将引发异常。同样,路径或路径的组合不能被完全限定两次。例如,“c:\temp c:\windows”在大多数情况下也将引发异常。在使用接受路径字符串的方法时,请确保路径是格式良好的。

在接受路径的成员中,路径可以是指文件或仅是目录。指定路径也可以是相对路径或者服务器和共享名称的统一命名约定 (UNC) 路径。例如,以下都是可接受的路径:

  • C# 中的“c:\\MyDir”或 Visual Basic 中的“c:\MyDir”。

  • C# 中的“MyDir\\MySubdir”或 Visual Basic 中的“MyDir\MySubDir”。

  • C# 中的“\\\\MyServer\\MyShare”或 Visual Basic 中的“\\MyServer\MyShare”。

默认情况下,向所有用户授予对新目录的完全读/写访问权限。如果在以目录分隔符结尾的路径字符串处要求提供某个目录的权限,会导致要求提供该目录所含的所有子目录的权限,如“C:\Temp\”。如果仅需要某个特定目录的权限,则该字符串应该以“.”字符结尾(例如“C:\Temp\.”)。

下表列出了其他典型或相关的 I/O 任务的示例。

若要执行此操作...

请参见本主题中的示例...

创建文本文件。

如何:向文件写入文本

写入文本文件。

如何:向文件写入文本

读取文本文件。

如何:从文件读取文本

重命名或移动目录。

Directory.Move

DirectoryInfo.MoveTo

删除目录。

Directory.Delete

DirectoryInfo.Delete

创建目录。

CreateDirectory

Directory

创建子目录。

CreateSubdirectory

查看目录中的文件。

Name

查看目录的子目录。

GetDirectories

GetDirectories

查看目录的所有子目录中的所有文件。

GetFileSystemInfos

查看目录大小。

Directory

确定文件是否存在。

Exists

按大小对目录中的文件排序。

GetFileSystemInfos

确定目录是否存在。

Exists

示例

下面的代码示例确定指定的目录是否存在,如果存在,则删除该目录;如果不存在,则创建该目录。然后,此示例将移动此目录,在其中创建一个文件并对文件进行计数。

Imports System
Imports System.IO

Public Class Test

    Public Shared Sub Main()
        'Specify the directories you want to manipulate.
        Dim path As String = "c:\MyDir"
        Dim target As String = "c:\TestDir"

        Try
            ' Determine whethers the directory exists.
            If Directory.Exists(path) = False Then
                ' Create the directory.
                Directory.CreateDirectory(path)
            End If

            If Directory.Exists(target) Then
                ' Delete the target to ensure it is not there.
                Directory.Delete(target, True)
            End If

            ' Move the directory.
            Directory.Move(path, target)

            'Create a file in the directory.
            File.CreateText(target + "\myfile.txt")

            'Count the files in the target.
            Console.WriteLine("The number of files in {0} is {1}", _
              target, Directory.GetFiles(target).Length)

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        // Specify the directories you want to manipulate.
        string path = @"c:\MyDir";
        string target = @"c:\TestDir";

        try 
        {
            // Determine whether the directory exists.
            if (!Directory.Exists(path)) 
            {
                // Create the directory it does not exist.
                Directory.CreateDirectory(path);
            }

            if (Directory.Exists(target)) 
            {
                // Delete the target to ensure it is not there.
                Directory.Delete(target, true);
            }

            // Move the directory.
            Directory.Move(path, target);

            // Create a file in the directory.
            File.CreateText(target + @"\myfile.txt");

            // Count the files in the target directory.
            Console.WriteLine("The number of files in {0} is {1}",
                target, Directory.GetFiles(target).Length);
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        } 
        finally {}
    }
}
using namespace System;
using namespace System::IO;
int main()
{
   
   // Specify the directories you want to manipulate.
   String^ path = "c:\\MyDir";
   String^ target = "c:\\TestDir";
   try
   {
      
      // Determine whether the directory exists.
      if (  !Directory::Exists( path ) )
      {
         
         // Create the directory it does not exist.
         Directory::CreateDirectory( path );
      }
      if ( Directory::Exists( target ) )
      {
         
         // Delete the target to ensure it is not there.
         Directory::Delete( target, true );
      }
      
      // Move the directory.
      Directory::Move( path, target );
      
      // Create a file in the directory.
      File::CreateText( String::Concat( target, "\\myfile.txt" ) );
      
      // Count the files in the target directory.
      Console::WriteLine( "The number of files in {0} is {1}", target, Directory::GetFiles( target )->Length );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( "The process failed: {0}", e );
   }

}
import System.*;
import System.IO.*;

class Test
{
    public static void main(String[] args)
    {
        // Specify the directories you want to manipulate.
        String path = "c:\\MyDir";
        String target = "c:\\TestDir";

        try {
            // Determine whether the directory exists.
            if (!(Directory.Exists(path))) {
                // Create the directory it does not exist.
                Directory.CreateDirectory(path);
            }

            if (Directory.Exists(target)) {
                // Delete the target to ensure it is not there.
                Directory.Delete(target, true);
            }

            // Move the directory.
            Directory.Move(path, target);

            // Create a file in the directory.
            File.CreateText(target + "\\myfile.txt");

            // Count the files in the target directory.
            Console.WriteLine("The number of files in {0} is {1}", target,
                (Int32)Directory.GetFiles(target).length);
        }
        catch (System.Exception e) {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
        finally {
        }
    } //main
} //Test

下面的代码示例演示如何计算目录的大小。

' The following example calculates the size of a directory
' and its subdirectories, if any, and displays the total size
' in bytes.
Imports System
Imports System.IO
Imports Microsoft.VisualBasic



Public Class ShowDirSize

    Public Shared Function DirSize(ByVal d As DirectoryInfo) As Long
        Dim Size As Long = 0
        ' Add file sizes.
        Dim fis As FileInfo() = d.GetFiles()
        Dim fi As FileInfo
        For Each fi In fis
            Size += fi.Length
        Next fi
        ' Add subdirectory sizes.
        Dim dis As DirectoryInfo() = d.GetDirectories()
        Dim di As DirectoryInfo
        For Each di In dis
            Size += DirSize(di)
        Next di
        Return Size
    End Function 'DirSize

    Public Overloads Shared Sub Main(ByVal args() As String)
        If args.Length <> 1 Then
            Console.WriteLine("You must provide a directory argument at the command line.")
        Else
            Dim d As New DirectoryInfo(args(0))
            Console.WriteLine("The size of {0} and its subdirectories is {1} bytes.", d, DirSize(d))
        End If
    End Sub 'Main
End Class 'ShowDirSize
// The following example calculates the size of a directory
// and its subdirectories, if any, and displays the total size
// in bytes.

using System;
using System.IO;

public class ShowDirSize 
{
    public static long DirSize(DirectoryInfo d) 
    {    
        long Size = 0;    
        // Add file sizes.
        FileInfo[] fis = d.GetFiles();
        foreach (FileInfo fi in fis) 
        {      
            Size += fi.Length;    
        }
        // Add subdirectory sizes.
        DirectoryInfo[] dis = d.GetDirectories();
        foreach (DirectoryInfo di in dis) 
        {
            Size += DirSize(di);   
        }
        return(Size);  
    }
    public static void Main(string[] args) 
    {
        if (args.Length != 1) 
        {
            Console.WriteLine("You must provide a directory argument at the command line.");    
        } 
        else 
        {  
            DirectoryInfo d = new DirectoryInfo(args[0]);
            Console.WriteLine("The size of {0} and its subdirectories is {1} bytes.", d, DirSize(d));
        }
    }
}
// The following example calculates the size of a directory
// and its subdirectories, if any, and displays the total size
// in bytes.
using namespace System;
using namespace System::IO;
long DirSize( DirectoryInfo^ d )
{
   long Size = 0;
   
   // Add file sizes.
   array<FileInfo^>^fis = d->GetFiles();
   System::Collections::IEnumerator^ myEnum = fis->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      FileInfo^ fi = safe_cast<FileInfo^>(myEnum->Current);
      Size += (long)fi->Length;
   }

   array<DirectoryInfo^>^dis = d->GetDirectories();
   while ( myEnum->MoveNext() )
   {
      DirectoryInfo^ di = safe_cast<DirectoryInfo^>(myEnum->Current);
      Size += DirSize( di );
   }

   return Size;
}

int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   if ( args->Length != 2 )
   {
      Console::WriteLine( "You must provide a directory argument at the command line." );
   }
   else
   {
      DirectoryInfo^ d = gcnew DirectoryInfo( args[ 1 ] );
      Console::WriteLine( "The size of {0} and its subdirectories is {1} bytes.", d, DirSize( d ) );
   }
}

继承层次结构

System.Object
  System.IO.Directory

线程安全

此类型的任何公共静态(Visual Basic 中的 Shared)成员都是线程安全的,但不保证所有实例成员都是线程安全的。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

Directory 成员
System.IO 命名空间
File
DirectoryInfo
FileInfo

其他资源

文件和流 I/O
如何:从文件读取文本
如何:向文件写入文本
基本的文件 I/O
如何:对新建的数据文件进行读取和写入