Search code examples
c#.netdirectoryinfogetfiles

DirectoryInfo.GetFiles() is not returning all files on desktop(it excludes shortcuts)


I have a listBox1 that should display all the files on my desktop, i have used the following method to do so

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo path = new DirectoryInfo(filepath);

foreach (var file in path.GetFiles())
{
    listBox1.Items.Add("File : " + file.Name);
}

It works but for some reason it doesn't display some shortcuts, it displays a few shortcuts but most of them are not displayed. I have no idea why this is happening


Solution

  • You are probably missing the shortcuts in the "All Users" desktop:

    string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    DirectoryInfo path = new DirectoryInfo(filepath);
    
    foreach (var file in path.GetFiles())
    {
        listBox1.Items.Add("File : " + file.Name);
    }
    
    //  Get files in the "common" desktop
    filepath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
    path = new DirectoryInfo(filepath);
    
    foreach (var file in path.GetFiles())
    {
        listBox1.Items.Add("File : " + file.Name);
    }
    

    You can refactor to combine the common code if that works.