目录类Directory

目录类用于许多操作,例如复制,移动,重命名,删除和创建目录。
目录也用于获取有关创建,访问和写入目录的日期时间信息。
换句话说,我们可以说目录类主要用于创建目录,删除目录,移动目录,在目录中创建文件,从目录中删除文件,计算目录中的文件数量和目录的数量计算文件大小和目录等

目录类的方法是静态的。
目录类的静态方法对所有方法执行安全检查。
如果我们要在几次使用相应的实例方法DirectoryInfo考虑几次重复使用对象。
因为安全检查并不总是必要的。
如果我们希望仅执行一个操作,字典方法可能会更有效。
大多数目录都需要我们操作的目录的路径。

在接受路径的成员中,路径可以指代文件或者只是一个目录。
指定的路径还可以参考服务器和共享名称的相对路径或者通用命名约定(UNC)路径。
例如,所有以下内容都是可接受的路径:

"c:\Dire" , "Dire\Subdire" , "\\MyServer\MyShare"

借助于所有用户授予对新目录的完整读/写访问权限。
要求允许路径字符串以目录分隔符的目录结束的目录权限导致所有包含的子目录的苛刻权限(例如,"c:\temp ")。
如果仅针对特定目录需要权限,则字符串应以句点结束(例如,"c:\temp \。
")。

C# 目录类示例

下面的示例判断了目录是否存在,如果不存在则删除它并创建它。本例还定义了移动目录、在目录中创建文件,并统计目录中的文件数量。

using System;
using System.IO;

class Demo 
{
    public static void Main() 
    {
        //Specify the directories you want to manipulate.
        string path = @"c:\Dire";
        string Dest = @"c:\Dest";

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

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

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

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

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

以下示例说明如何计算目录的大小

using System;
using System.IO;

public class DireSize
{
    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]);
            long dsize = DirSize(d);
            Console.WriteLine("The size of {0} and its subdirectories is {1} bytes.", d, dsize);
        }
    }
}
C# 目录类Directory
日期:2020-04-11 22:50:27 来源:oir作者:oir