getting the full filenames from all top directory files in a specific directory and suppressing the occuring error

StackOverflow https://stackoverflow.com/questions/18071587

Question

I met a not expected problem with getting just the top directory full filenames from a specific directory. C# throws an error and doesn't list anything in the specific directory. But MS DOS has not a problem with my command: *"dir C:\windows\prefetch\*.pf"

Visual Basics 6 old "Dir Function" also does it without complaining. The "Windows Explorer" opens it up and doesn't ask anything from me. Also "Nirsofts Tool Suit" lists it instantly without any problem. No one of this tools needs to run with special permissions, just a double click on the application icon and ready is the task.

I looked around and found nothing here, what would answer this weird problem. My user can access the directory, if I go with any other application into it, now there is the question why C# throws an "Unauthorized Access Exception" which is totally weird, since I have access in this folder.

I don't want to elevate my application with admin permissions for it nor create extra a xml for it to run it with highest privileges. The not trustful yellow elevation box must be avoided.

Now my question: How it comes that I can not list the filenames in this folder when all other applications can do that. What code do I need if "Directory.GetFiles()" fails? Is there any flag or property in the framework directory class which allows my application access to the files, whatever.

Here my code which fails (using System.IO):

private void button1_Click(object sender, EventArgs e)
    {

        textBox1.Text = textBox1.Text.Substring(0, 0); //clear the textBox1

        //Unauthorized access exception and yellow bar in this line
        foreach(string FileX in Directory.GetFiles(Path.Combine(Environment.GetEnvironmentVariable("windir"), "prefetch"), "*.pf"))
        {
            textBox1.Text += FileX;
        }
    }
Was it helpful?

Solution

Did I understand correctly that you only need the File-names with directory-names. This code works for me, no elevations needed.

 private void button1_Click(object sender, EventArgs e)
    {
        string folder = @"C:\windows\prefetch";
        string filemask = @"*.pf";
        string[] filelist = Directory.GetFiles(folder, (filemask));

        //now use filelist[i] for any operations. 
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top