標籤:des style blog http color io os ar for
通過指定路徑訪問路徑下的檔案,在C#的開發中主要利用了Directory類和DirectoryInfo類,簡要介紹Directory類中的成員:命名空間
System.IO 命名空間
1、CreateDirectory,已重載,用於建立指定路徑下的所有目錄;
2、Delete,刪除指定目錄;
3、Exists,確定給定目錄是否引用磁碟現有目錄;說白點就是判斷路徑是否存在;
4、GetCreationTime,擷取目錄的建立時間和日期;
4、GetCurrentDirectory,擷取應用程式的目前的目錄;
5、GetDirectories,擷取指定目錄下子目錄的名稱,返回值是一個字串數組;
6、GetFiles,擷取指定路徑下的檔案名稱;
7、GetFileSystemEntries,擷取指定路徑下所有檔案和子目錄的名稱;
8、GetParent,擷取指定路徑的父目錄;
9、Move,將檔案或目錄移動到新位置;
(2)簡要介紹下DirectoryInfo類的成員:
1、Create,建立指定目錄;
2、Delete,從路徑中刪除DirectoryInfo和其內容
3、GetDirectories,擷取目前的目錄的子目錄;
4、GetFiles,擷取目前的目錄下的檔案清單;返回FileInfo[]類型的數組;
5、MoveTo,將DirectoryInfo 執行個體及其內容移動到新路徑。
代碼實現:
/// <summary> /// 開啟檔案 /// </summary> private void bePath_Click(object sender, EventArgs e) { this.MenuList.Nodes.Clear(); FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog(); folderBrowserDialog.Description = "請選擇目錄:"; if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { sPath = folderBrowserDialog.SelectedPath; } if (!string.IsNullOrEmpty(sPath)) { this.bePath.Text = sPath; TreeListNode ParentNode = this.MenuList.AppendNode(new object[] { sPath }, -1); GetSubFile(sPath, ParentNode); GetSubRoot(sPath, ParentNode); } }
/// <summary> /// 擷取路徑的集合 /// </summary> /// <param name="sPath"></param> private void GetSubRoot(string sFilePath, TreeListNode ParentNode) { if (string.IsNullOrEmpty(sFilePath)) { return; } string[] DirectoryList = Directory.GetDirectories(sFilePath); foreach (string sDirectory in DirectoryList) { ParentNode = this.MenuList.AppendNode(new object[] { sDirectory }, ParentNode); GetSubFile(sDirectory,ParentNode); GetSubRoot(sDirectory,ParentNode); } }
/// <summary> /// 擷取路徑下的檔案 /// </summary> /// <param name="sSubRootPath"></param> /// <param name="ParentNode"></param> private void GetSubFile(string sSubRootPath, TreeListNode ParentNode) { FileInfo[] ArrayileInfo; DirectoryInfo pDirectoryInfo = new DirectoryInfo(sSubRootPath); ArrayileInfo = pDirectoryInfo.GetFiles("*."); if (ArrayileInfo.Length < 1) { return; } foreach (FileInfo pFileInfo in ArrayileInfo) { string sName = pFileInfo.Name; MenuList.AppendNode(new object[] { sName }, ParentNode); } }
C#遍曆指定路徑下的檔案夾