文件处理-Directory类 (C#)

系统 2289 0

转http://skybirdzw.blog.163.com/blog/static/7257062620099751329403/

文件处理-Directory类 (C#)  

Directory.CreateDirectory 方法:创建指定路径中的所有目录。

Directory.CreateDirectory (String) 按 path 的指定创建所有目录和子目录。

Directory.CreateDirectory (String, DirectorySecurity) 创建指定路径中的所有目录,并应用指定的 Windows 安全性。

//***************codeTest**************************************

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        // Specify the directory you want to manipulate.

        string path = @"c:\MyDir\MyDoc";

        try

        {

            // Determine whether the directory exists.

            if (Directory.Exists(path))

            {

                Console.WriteLine("That path exists already.");

                return;

            }

            // Try to create the directory.

            DirectoryInfo di = Directory.CreateDirectory(path);

            Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));

            // Delete the directory.

            //di.Delete();

            Console.WriteLine("The directory was deleted successfully.");

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

        finally { }

    }

}

//***************endCode**************************************

Directory.Delete 方法:删除指定的目录。

Directory.Delete (String) 从指定路径删除空目录。

Directory.Delete (String, Boolean) 删除指定的目录并(如果指示)删除该目录中的任何子目录。

//***************codeTest**************************************

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        // Specify the directories you want to manipulate.

        string path = @"c:\MyDir";

        string subPath = @"c:\MyDir\temp";

        try

        {

            // Determine whether the directory exists.

            if (!Directory.Exists(path))

            {

                // Create the directory.

                Directory.CreateDirectory(path);

            }

            if (!Directory.Exists(subPath))

            {

                // Create the directory.

                Directory.CreateDirectory(subPath);

            }

            // This will succeed because subdirectories are being deleted.

            Console.WriteLine("I am about to attempt to delete {0}", path);

            Directory.Delete(path, true);

            Console.WriteLine("The Delete operation was successful.");

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

        finally { }

    }

}

//***************endCode**************************************

Directory.Exists 方法:确定给定路径是否引用磁盘上的现有目录。

Directory.GetCreationTime 方法:获取目录的创建日期和时间。

//***************codeTest**************************************

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        try

        {

            // Get the creation time of a well-known directory.

            DateTime dt = Directory.GetCreationTime(Environment.CurrentDirectory);

            // Give feedback to the user.

            if (DateTime.Now.Subtract(dt).TotalDays > 364)

            {

                Console.WriteLine("This directory is over a year old.");

            }

            else if (DateTime.Now.Subtract(dt).TotalDays > 30)

            {

                Console.WriteLine("This directory is over a month old.");

            }

            else if (DateTime.Now.Subtract(dt).TotalDays <= 1)

            {

                Console.WriteLine("This directory is less than a day old.");

            }

            else

            {

                Console.WriteLine("This directory was created on {0}", dt);

            }

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

    }

}

//***************endCode**************************************

Directory.GetCurrentDirectory 方法:获取应用程序的当前工作目录。

//***************codeTest**************************************

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        try

        {

            // Get the current directory.

            string path = Directory.GetCurrentDirectory();

            string target = @"c:\temp";

            Console.WriteLine("The current directory is {0}", path);

            if (!Directory.Exists(target))

            {

                Directory.CreateDirectory(target);

            }

            // Change the current directory.

            Environment.CurrentDirectory = (target);

            if (path.Equals(Directory.GetCurrentDirectory()))

            {

                Console.WriteLine("You are in the temp directory.");

            }

            else

            {

                Console.WriteLine("You are not in the temp directory.");

            }

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

    }

}

//***************endCode**************************************

Directory.GetDirectories 方法:获取指定目录中子目录的名称。

Directory.GetDirectories (String) 获取指定目录中子目录的名称。

Directory.GetDirectories (String, String) 从当前目录获取与指定搜索模式匹配的目录的数组。

Directory.GetDirectories (String, String, SearchOption) 获取当前目录中与指定搜索模式匹配并使用某个值确定是否在子目录中搜索的目录的数组。

//***************codeTest**************************************

using System;

using System.IO;

class SubDir

{

    public static void Main()

    {

        string path = @"F:\课件\通信原理";

        try

        {

            string[] dirs = Directory.GetDirectories(path);

            Console.WriteLine("F:\\课件\\通信原理 子目录数 = {0}", dirs.Length);

            foreach (string dir in dirs)

                Console.WriteLine(dir);

        }

        catch (Exception e)

        {

            Console.WriteLine("失败: {0}", e.ToString());

        }

    }

}

//***************endCode**************************************

//***************codeTest**************************************

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        try

        {

            // Only get subdirectories that begin with the letter "p."

            string[] dirs = Directory.GetDirectories(@"c:\", "p*");

            Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length);

            foreach (string dir in dirs)

            {

                Console.WriteLine(dir);

            }

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

    }

}

//***************endCode**************************************

Directory.GetFiles 方法:返回指定目录中的文件的名称。

Directory.GetFiles (String) 返回指定目录中的文件的名称。

Directory.GetFiles (String, String) 返回指定目录中与指定搜索模式匹配的文件的名称。

Directory.GetFiles (String, String, SearchOption) 返回指定目录中文件的名称,该目录与指定搜索模式匹配并使用某个值确定是否在子目录中搜索。

//***************codeTest**************************************

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        try

        {

            // Only get files that begin with the letter "c."

            string[] dirs = Directory.GetFiles(@"F:\memo","*.txt");

            Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);

            foreach (string dir in dirs)

            {

                Console.WriteLine(dir);

            }

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

    }

}

//***************endCode**************************************

Directory.GetFileSystemEntries 方法:返回指定目录中所有文件和子目录的名称。

Directory.GetFileSystemEntries (String) 返回指定目录中所有文件和子目录的名称。

Directory.GetFileSystemEntries (String, String) 返回与指定搜索条件匹配的文件系统项的数组。

Directory.Move 方法:将文件或目录及其内容移到新位置。

//***************codeTest**************************************

using System;

using System.IO;

class Test

{

    public static void Main()

    {

        try

        {

            string path = @"F:\memo";

            string path2 = @"F:\VC++串口通讯\memo";

            Directory.Move(path, path2);

        }

        catch (Exception e)

        {

            Console.WriteLine("The process failed: {0}", e.ToString());

        }

    }

}

//***************endCode**************************************

举 例来讲,如果您尝试将 c:\mydir 移到 c:\public,并且 c:\public 已存在,则此方法引发 IOException。您必须将“c:\\public\\mydir”指定为 destDirName 参数(假设“c:\\public”下不存在“mydir”),或者指定一个新的目录名,例如“c:\\newdir”。

//***************codeTest**************************************

using System;

namespace GetFileSystemEntries

{

    class Class1

    {

        static void Main(string[] args)

        {

            Class1 snippets = new Class1();

            string path = System.IO.Directory.GetCurrentDirectory();

            string filter = "*.exe";

            snippets.PrintFileSystemEntries(path);

            snippets.PrintFileSystemEntries(path, filter);

            snippets.GetLogicalDrives();

            snippets.GetParent(path);

            snippets.Move("C:\\proof", "C:\\Temp");

        }

        void PrintFileSystemEntries(string path)

        {

            try

            {

                // Obtain the file system entries in the directory path.

                string[] directoryEntries =

                    System.IO.Directory.GetFileSystemEntries(path);

                foreach (string str in directoryEntries)

                {

                    System.Console.WriteLine(str);

                }

            }

            catch (ArgumentNullException)

            {

                System.Console.WriteLine("Path is a null reference.");

            }

            catch (System.Security.SecurityException)

            {

                System.Console.WriteLine("The caller does not have the " +

                    "required permission.");

            }

            catch (ArgumentException)

            {

                System.Console.WriteLine("Path is an empty string, " +

                    "contains only white spaces, " +

                    "or contains invalid characters.");

            }

            catch (System.IO.DirectoryNotFoundException)

            {

                System.Console.WriteLine("The path encapsulated in the " +

                    "Directory object does not exist.");

            }

        }

        void PrintFileSystemEntries(string path, string pattern)

        {

            try

            {

                // Obtain the file system entries in the directory

                // path that match the pattern.

                string[] directoryEntries =

                    System.IO.Directory.GetFileSystemEntries(path, pattern);

                foreach (string str in directoryEntries)

                {

                    System.Console.WriteLine(str);

                }

            }

            catch (ArgumentNullException)

            {

                System.Console.WriteLine("Path is a null reference.");

            }

            catch (System.Security.SecurityException)

            {

                System.Console.WriteLine("The caller does not have the " +

                    "required permission.");

            }

            catch (ArgumentException)

            {

                System.Console.WriteLine("Path is an empty string, " +

                    "contains only white spaces, " +

                    "or contains invalid characters.");

            }

            catch (System.IO.DirectoryNotFoundException)

            {

                System.Console.WriteLine("The path encapsulated in the " +

                    "Directory object does not exist.");

            }

        }

        // Print out all logical drives on the system.

        void GetLogicalDrives()

        {

            try

            {

                string[] drives = System.IO.Directory.GetLogicalDrives();

                foreach (string str in drives)

                {

                    System.Console.WriteLine(str);

                }

            }

            catch (System.IO.IOException)

            {

                System.Console.WriteLine("An I/O error occurs.");

            }

            catch (System.Security.SecurityException)

            {

                System.Console.WriteLine("The caller does not have the " +

                    "required permission.");

            }

        }

        void GetParent(string path)

        {

            try

            {

                System.IO.DirectoryInfo directoryInfo =

                    System.IO.Directory.GetParent(path);

                System.Console.WriteLine(directoryInfo.FullName);

            }

            catch (ArgumentNullException)

            {

                System.Console.WriteLine("Path is a null reference.");

            }

            catch (ArgumentException)

            {

                System.Console.WriteLine("Path is an empty string, " +

                    "contains only white spaces, or " +

                    "contains invalid characters.");

            }

        }

        void Move(string sourcePath, string destinationPath)

        {

            try

            {

                System.IO.Directory.Move(sourcePath, destinationPath);

                System.Console.WriteLine("The directory move is complete.");

            }

            catch (ArgumentNullException)

            {

                System.Console.WriteLine("Path is a null reference.");

            }

            catch (System.Security.SecurityException)

            {

                System.Console.WriteLine("The caller does not have the " +

                    "required permission.");

            }

            catch (ArgumentException)

            {

                System.Console.WriteLine("Path is an empty string, " +

                    "contains only white spaces, " +

                    "or contains invalid characters.");

            }

            catch (System.IO.IOException)

            {

                System.Console.WriteLine("An attempt was made to move a " +

                    "directory to a different " +

                    "volume, or destDirName " +

                    "already exists.");

            }

        }

    }

}

//***************endCode**************************************

Notice: Codes were mainly from MSDN

文件处理-Directory类 (C#)


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论