i wrote an application which is a custom console that allows execution of various commands. One of the commands allows to find a file's full path, according to part of its name. The input data is a string, which equals to part\full name of the file.

My question is - how to minimize the search code runtime complexity as much as possible?

Here is the command's code:

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.A­llDirectories))
                {
                    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;
        }
    }
}

Example - for the input parameters "c:\temp test", the output can be:

The file found in path: c:\temp\test.json
The file found in path: c:\temp\test.json
The file found in path: c:\temp\test.xml
The file found in path: c:\temp\test.json
The file found in path: c:\temp\test.xml
The file found in path: c:\temp\test\test.json

1 Answers

2
Azzy Elvul On Best Solutions

You can simply your foreach like this

var fileLocations  =  Directory.GetFiles(initialLocation, $"{filePath}.*", SearchOption.A­llDirectories);

 foreach (var location in fileLocations)
 {
       returnedOutput += $"The file found in path: {location}\n";
       Console.Write(returnedOutput);
 }

The rest of the code also can be simplified.