当前位置: 移动技术网 > IT编程>开发语言>.net > C#获取某一路径下的所有文件名信息(包括子文件夹)

C#获取某一路径下的所有文件名信息(包括子文件夹)

2018年07月04日  | 移动技术网IT编程  | 我要评论

真命天妃全集,中医美白养颜全方略,xingshenghuozhinan

贴代码了,这里使用的是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();
        }
    }
}

 

控制台信息截图:

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网