2023-02-24 ChatGpt 生成检索文件的方法
2023-02-23 本文已影响0人
1f658716b568
using System;
using System.IO;
using System.Threading.Tasks;
namespace SearchObjFiles
{
class Program
{
static async Task Main(string[] args)
{
try
{
// Ask the user to enter the directory to search
Console.WriteLine("请输入要搜索的目录:");
string dir = Console.ReadLine();
// Validate the directory input
if (string.IsNullOrEmpty(dir))
{
throw new ArgumentException("目录不能为空。");
}
if (!Directory.Exists(dir))
{
throw new DirectoryNotFoundException("目录不存在。");
}
// Ask the user to enter the file extension to search for
Console.WriteLine("请输入要搜索的文件扩展名:");
string ext = Console.ReadLine();
// Validate the file extension input
if (string.IsNullOrEmpty(ext))
{
throw new ArgumentException("文件扩展名不能为空。");
}
// Ask the user to enter the output file name
Console.WriteLine("请输入输出文件的名称:");
string output = Console.ReadLine();
// Validate the output file name input
if (string.IsNullOrEmpty(output))
{
throw new ArgumentException("输出文件名称不能为空。");
}
// Ask the user to enter whether to search subdirectories or not
Console.WriteLine("是否要搜索子目录?(y/n)");
string option = Console.ReadLine();
// Validate and parse the option input
SearchOption searchOption;
switch (option.ToLower())
{
case "y":
searchOption = SearchOption.AllDirectories;
break;
case "n":
searchOption = SearchOption.TopDirectoryOnly;
break;
default:
throw new ArgumentException("无效的选项,请输入y或n。");
}
// Get all files with the specified extension in the directory and subdirectories
string[] files = Directory.GetFiles(dir, "*" + ext, searchOption);
// Write the file names and paths to the output file asynchronously
using (StreamWriter sw = new StreamWriter(output))
{
foreach (string file in files)
{
await sw.WriteLineAsync(file);
}
}
// Display a success message
Console.WriteLine("检索完成,共找到{0}个文件,已写入{1}。", files.Length, output);
}
catch (Exception ex)
{
// Display an error message
Console.WriteLine("发生错误:{0}", ex.Message);
}
}
}
}