Directory クラスとは? わかりやすく解説

Directory クラス

ディレクトリサブディレクトリ通じて作成移動、および列挙するための静的メソッド公開します。このクラス継承できません。

名前空間: System.IO
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

解説解説

Directory クラスは、ディレクトリコピー移動、名前変更作成削除などの一般的な操作使用しますDirectory クラスは、ディレクトリ対す作成アクセス、および書き込み操作についてDateTime 情報取得および設定にも使用できます

Directoryメソッドはすべて静的であるため、1 つ操作実行するだけであればDirectoryメソッド使用する方が、対応する DirectoryInfo のインスタンス メソッド使用するよりも効率的な場合ありますDirectoryメソッドのほとんどは、操作対象ディレクトリパスを必要とします

Directory クラス静的メソッドは、すべてのメソッドセキュリティ チェック実行しますオブジェクト何回再利用する場合は、このようなセキュリティ チェックが必ずしも必要ではなくなるため、これらの静的メソッド代わりに DirectoryInfo対応するインスタンス メソッド使用することを検討してください

メモメモ

入力文字列としてパス受け入れメンバでは、そのパス正し書式である必要がありますそれ以外場合は、例外発生します。たとえば、パス絶対パスであっても空白始まっている場合、そのパスクラスメソッドではトリムされません。このためパス正し書式にならず、例外発生します同様に1 つパスまたは複数パス組み合わせ絶対パスとして 2 度指定することはできません。たとえば、"c:\temp c:\windows" でも、ほとんどの場合において例外発生しますパス文字列受け入れメソッド使用するときは、パス適切な書式であることを確認します

パス受け入れメンバでは、ファイルまたはディレクトリ参照するパス指定できます指定するパスは、相対パス、またはサーバーおよび共有名を示す UNC (Universal Naming Convention) パスにすることができます。たとえば、次に示すパスはすべて有効なパスです。

既定では、すべてのユーザーに、新しディレクトリ対する完全な読み書きアクセス権与えられます。パス文字列ディレクトリ区切り記号で終わるディレクトリ対すアクセス許可要求すると、結果として、そのディレクトリ含まれるすべてのサブディレクトリ対すアクセス許可要求することになります ("C:\Temp\" など)。特定のディレクトリ対すアクセス許可のみが必要な場合は、文字列を "." 文字終わらせる必要があります ("C:\Temp\." など)。

その他の一般的な I/O タスクまたは関連する I/O タスクの例を次の表に示します

使用例使用例

指定したディレクトリ存在するかどうか判断して存在する場合はそれを削除し存在しない場合はそれを作成するコード例次に示します。この例では、この後ディレクトリ移動しディレクトリ内にファイル作成しディレクトリ内のファイルの数をカウントます。

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
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「Directory クラス」の関連用語

Directory クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Directory クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS