MdSalehGh
MdSalehGh

Reputation: 41

c# - Any way to get list of files in a logical drive ( path error )?

I'm writing an app for myself that backup the files which I've chosen before! I select which logical drives to add to a list and it should get list of files in the path and do the other stuff I told it :)

I can possibly say that i searched all the web! I tried to combine path, get driveinfo and ..... last code I, trying is this :

foreach (var drivename in driveslist)
{
    string[] files = Directory.GetFiles(drivename, "*.*");
}

Edit: driveslist contains:

C
E
D

System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\ E'.'

Upvotes: 1

Views: 346

Answers (2)

FishySwede
FishySwede

Reputation: 1583

It seems GetFiles doesn't understand that it is a drive you want to list.

Try ensuring you driveslist contains something like {@"C:\", @"D:\"} etc.

Edit: Or if you're not in control of the upstream list just do:

foreach (var drivename in driveslist)
{
     string[] files = Directory.GetFiles($"{drivename}:\\", "*.*");
}

Edit2: I'm very surprised this doesn't work. the following code works on my machine:

class Program
{
    static void Main(string[] args)
    {
        var driveslist = new[] {"C"};

        foreach (var drivename in driveslist)
        {
            string[] files = Directory.GetFiles($"{drivename}:\\", "*.*");
            foreach (var file in files)
            {
                Console.WriteLine(file);
            }
        }
        Console.ReadLine();
    }
}

Upvotes: 3

Robin Bennett
Robin Bennett

Reputation: 3231

That sounds as if driveslist contains the string 'C:\ E', which isn't a valid path.

I just tried:

string[] files = Directory.GetFiles("c:\\", "*.*");

and it works. I think you're blaming GetFiles but the problem is actually in the path.

If you just ask for e (without the colon and slash) it will think you want a subfolder called e of the current directory.

Upvotes: 0

Related Questions