1. 程式人生 > >[C#學習筆記]判斷檔案資料夾是否存在

[C#學習筆記]判斷檔案資料夾是否存在

判斷檔案或者資料夾是否存在

   首先,檔案File,資料夾Directory,需要引用System.IO

using System.IO;
    定義一個需要判斷的檔案的地址
string filePath = "C:\\test.txt" ;
    然後利用File進行判斷
            if (File.Exists(filePath))
            {
                Console.WriteLine("檔案{0}存在.", filePath);
            }
            else
            {
                Console.WriteLine("檔案{0}不存在.", filePath);
            }

   執行結果如下圖所示


   定義一個資料夾的地址

string folderPath ="C:\\Windows";

    利用Directory進行判定
            string folderPath = "C:\\Windows";
            if (Directory .Exists (folderPath ))
            {
                Console.WriteLine(" 資料夾{0}存在.", folderPath);
            }
            else 
            {
                Console.WriteLine("資料夾{0}不存在.", folderPath);
            }
            Console.ReadKey();
    執行結果如下圖