1. 程式人生 > >C#獲取某一路徑下的所有文件名信息(包括子文件夾)

C#獲取某一路徑下的所有文件名信息(包括子文件夾)

txt 技術 ont getc des lena ssa rect cati

貼代碼了,這裏使用的是C#控制臺輸出文件名到記事本中,文件名使用逗號隔開:

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        public static string FileName = "";

        public static void Main(string[] args)
        {
            bool isContinute = true;
            WriteMessage("結束程序請輸入1
"); WriteMessage("請輸入要獲取文件名的路徑:"); string path = Console.ReadLine(); do { if (string.IsNullOrEmpty(path)) { WriteMessage("路徑不存在!請重新輸入"); } else { DirectoryInfo dir
= new DirectoryInfo(path); if (dir.Exists == false) { WriteMessage("路徑不存在!請重新輸入"); } else { FileName = ""; GetChildDicsName(dir); WriteMessage(FileName); Console.WriteLine(
"獲取該路徑下文件名成功!你可以繼續輸入新的路徑"); } } path = Console.ReadLine(); isContinute = path != "1"; } while (isContinute); } public static DirectoryInfo[] GetChildDicsName(DirectoryInfo dir) { FileInfo[] fileArray = dir.GetFiles(); DirectoryInfo[] childDirs = dir.GetDirectories(); foreach (FileInfo file in fileArray) { FileName += file.Name + ","; } if (childDirs.Length > 0) { foreach (DirectoryInfo dirChild in childDirs) { GetChildDicsName(dirChild); } } return childDirs; } public static void WriteMessage(string message) { Console.WriteLine(message); //File.Create(@"C:\Users\Public\Desktop\test.txt"); FileStream fs = File.Open(@"C:\Users\Public\Desktop\test.txt", FileMode.Append); StreamWriter sw = new StreamWriter(fs); sw.WriteLine(message); //這裏是寫入的內容 sw.Close(); fs.Close(); } } }

控制臺信息截圖:

技術分享圖片

C#獲取某一路徑下的所有文件名信息(包括子文件夾)