Directory類提供的靜態方法去處理目錄

iamzxf發表於2015-06-03


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

namespace directoryDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string path1 = @"d:\csharp\mydir";
            string path2 = @"d:\csharp\mydesdir";

            try
            {
                Console.WriteLine("當前目錄為:{0}",Directory.GetCurrentDirectory());
                Console.WriteLine("上次訪問當前目錄的時間為:{0}",Directory.GetLastAccessTime(Directory.GetCurrentDirectory()));
                if (Directory.Exists(path1))
                    Console.WriteLine(path1 + "已存在");
                else {
                    Console.WriteLine("不存在,準備建立");
                    DirectoryInfo dir = Directory.CreateDirectory(path1);
                    DateTime dtime = new DateTime(2015, 6, 4);
                    Directory.SetCreationTime(path1, dtime);
                }

                Console.WriteLine("========================");
                Console.WriteLine("目錄建立時間為:{0}", Directory.GetCreationTime(path1));
                Console.WriteLine("其根目錄為:{0}",Directory.GetDirectoryRoot(path1));

                if (!Directory.Exists(path2))
                {
                    Console.WriteLine("目錄不存在時可以重新命名");
                    Directory.Move(path1, path2);
                    Console.WriteLine("{0}重新命名為{1}", path1, path2);
                }
                else
                    Console.WriteLine("目錄存在,無法重新命名");

                Console.WriteLine("========================");
                string root = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
                string[] subDirectory = Directory.GetDirectories(root);

                foreach (string str in subDirectory)
                    Console.WriteLine(str);

            }
            catch (Exception e)
            {
                Console.WriteLine("操作失敗:{0}",e.ToString());
            }

            Console.ReadLine();
        }
    }
}



相關文章