我编写了一个应用程序,该应用程序是一个允许执行各种命令的自定义控制台。其中一个命令允许根据其名称的一部分找到文件的完整路径。输入数据是一个字符串,其等于文件的部分全名。
我的问题是 - 如何尽可能最小化搜索代码运行时复杂性?
这是命令的代码:
using CustomConsole.Common;
using System;
using System.Collections.Generic;
using System.IO;
namespace Shell_Commander.Commands
{
class FindFileCommand : ICommand
{
private string _findFileCommandName = "findfile";
public string Name { get { return _findFileCommandName; } set { _findFileCommandName = value; } }
public string Execute(string parameters)
{
var fileLocations = new Dictionary<string, bool>();
try
{
var splittedParameters = parameters.Split(" ");
var initialLocation = splittedParameters[0];
var fileName = splittedParameters[1];
foreach (var filePath in Directory.GetFiles(initialLocation, "*.*", SearchOption.AllDirectories))
{
fileLocations.Add(filePath, false);
if (Path.GetFileName(filePath) == fileName || Path.GetFileNameWithoutExtension(filePath) == fileName)
{
fileLocations[filePath] = true;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
bool fileFound = false;
string returnedOutput = "";
foreach (var location in fileLocations.Keys)
{
if (fileLocations[location])
{
returnedOutput += $"The file found in path: {location}n";
Console.Write(returnedOutput);
fileFound = true;
}
}
if (!fileFound)
{
returnedOutput = "The file not found in this path";
Console.WriteLine(returnedOutput);
return returnedOutput;
}
return returnedOutput;
}
}
}
示例 - 对于输入参数" C: temp Test",输出可以是:
The file found in path: c:temptest.json
The file found in path: c:temptest.json
The file found in path: c:temptest.xml
The file found in path: c:temptest.json
The file found in path: c:temptest.xml
The file found in path: c:temptesttest.json
您可以简单地像这样
var fileLocations = Directory.GetFiles(initialLocation, $"{filePath}.*", SearchOption.AllDirectories);
foreach (var location in fileLocations)
{
returnedOutput += $"The file found in path: {location}n";
Console.Write(returnedOutput);
}
其余代码也可以简化。