You must Sign In to post a response.
  • Category: .NET

    Find the string within List<string>

    Hi,

    I have load all the files from folder and it's sub folder and kept in List<string>. I want to search the file name in this List<string> how can i do this from button click(button6). below is the code..

    private void button5_Click(object sender, EventArgs e)
    {
    List<string> allFiles = GettingFiles(@"c:\");
    }
    private void button6_Click(object sender, EventArgs e)
    {

    }
    public static List<string> GettingFiles(string path)
    {
    List<string> listFiles = new List<string>();

    //1. get files from the current directory:
    string[] currentFiles = Directory.GetFiles(path, "*.*");
    foreach (string file in currentFiles)
    listFiles.Add(file);
    //2. get files from other sub directories:
    string[] directories = Directory.GetDirectories(path);
    foreach (string dir in directories)
    {
    string[] files = GetFilesFromDirectory(dir);
    listFiles.AddRange(files);
    }
    //for the end, lets get only the names of the files (remove the path):
    for (int i = 0; i < listFiles.Count; i++)
    {
    string fileName = Path.GetFileName(listFiles[i]);
    listFiles[i] = fileName;
    }

    return listFiles;
    }

    private static string[] GetFilesFromDirectory(string path)
    {
    string[] files = Directory.GetFiles(path);
    return files;
    }
  • #768923
    Hai Gopi,
    If you want to find-out the string which in inside List<string>, you can use Contains method to do that.
    e.g.

    if (listFiles.Contains("fileName", StringComparer.OrdinalIgnoreCase))

    Hope it will be helpful to you.

    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com

  • #768925
    Hi Pawan,

    Thanks, Actually i will load all the files from directory and it's subdirectory at once. And loaded file name will be in "allFiles" based on the given path at runtime. While loading the files i will not search or compare the file names.

    List<string> allFiles = GettingFiles(@"c:\");

    After completed the loading, i will be search the file name (Note: frequently i will be searching the different file name). So, i think to searching the file again and again in the directory and subdirectory is not fine. It may take additional time. Instead, i would like to search the file name in the "allFiles" which is stored all data within it. I will pass the filename from another button click...

    As per your advice, i think the file will be search within the function "GettingFiles" which is searching in directory. I feel this will take some extra time. Please advice...

  • #768927
    Hi Pawan,

    I solved this. As i have assigned the List<string> as global variable afterwards i have used this in button click to get the file name. Thanks for your support.


  • Sign In to post your comments