日期:2014-05-17  浏览次数:21053 次

C#常用目录操作总结

在C#中,常用的目录操作类有Directory, DirectoryInfo,基本上两个类提供的方法大同小异,有不算太大的区别,但是Directory类是静态类,所有的函数都是静态函数,可以直接调用。


使用Directory可以创建指定的目录,删除目录,获取目录信息,例如创建时间等,获取目录中的子目录,获取目录中的文件集合等操作,还可以设置目录的访问时间等。


简单的一个目录操作的代码,判断目录是否存在,如果不存在则创建目录:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Users\watkins\Desktop\TcpListener\TcpListener\bin";
            bool a = Directory.Exists(path);
            if (!a)
            {
                Directory.CreateDirectory(path);
            }
            Console.WriteLine(a);
            Console.Read();
        }
    }
}


Directory类的成员列表:


Directory Members

Exposes static methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.

The Directory type exposes the following members.

Methods

  Name Description
Public methodSupported by the XNA Framework CreateDirectory(String) Creates all directories and subdirectories as specified by path.
Public method CreateDirectory(String, DirectorySecurity) Creates all the directories in the specified path, applying the specified Windows security.
Public methodSupported by the XNA Framework Delete(String) Deletes an empty directory from a specified path.
Public methodSupported by the XNA Framework Delete(String, Boolean) Deletes the specified directory and, if indicated, any subdirectories and files in the directory.
Public method EnumerateDirectories(String) Returns an enumerable collection of directory names in a specified path.
Public method EnumerateDirectories(String, String) Returns an enumerable collection of directory names that match a search pattern in a specified path.
Public method EnumerateDirectories(String, String, SearchOption) Returns an