C#获取某一路径下的所有文件名信息(包括子文件夹)
2021-03-31 14:28
标签:oid nbsp readline write end strong [] return open 贴代码了,这里使用的是C#控制台输出文件名到记事本中,文件名使用逗号隔开: 控制台信息截图: C#获取某一路径下的所有文件名信息(包括子文件夹) 标签:oid nbsp readline write end strong [] return open 原文地址:https://www.cnblogs.com/lxhbky/p/9254832.htmlusing 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#获取某一路径下的所有文件名信息(包括子文件夹)
文章链接:http://soscw.com/index.php/essay/70500.html