Marcin Kwarciński
Marcin Kwarciński

Reputation: 1

c# getting files form directory

i have problem with my c# code, i want to list all files from mozilla user data folder, i was trying to do it with:

String dir = Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Mozilla\\Firefox\\Profiles\\")[0];
string[] fileEntries = Directory.GetFiles(Environment.GetEnvironmentVariable("AppData") + "\\Mozilla\\Firefox\\Profiles\\" + dir);

But when i execute this code i get error that tells me that format of this path is not supported. In error info i can see that my path is:

"C:\Users\Marcin\AppData\Roaming\Mozilla\Firefox\Profiles\4wrivbme.default"

Its because of \? I'm sure that i need this.

Upvotes: 0

Views: 104

Answers (2)

Steve
Steve

Reputation: 216243

If I have understood correctly your code, then the second line should be just

string[] fileEntries = Directory.GetFiles(dir);

On my PC your second line gives back this path that is clearly wrong

C:\Users\steve\AppData\Roaming\Mozilla\Firefox\Profiles\C:\Users\steve\AppData.....
                                                      ^^^^^

So a full fix of your code should be as this

string mozillaProfilePath = Path.Combine(
  Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
                            "Mozilla\\Firefox\\Profiles");

string[] dirs = Directory.GetDirectories(mozillaProfilePath);
if(dirs.Length > 0)
{
    string[] fileEntries = Directory.GetFiles(dirs[0]);
    ......
}

and, if your process the result directly here, then it is better to use Directory.EnumeratFiles instead of GetFiles (See remarks in the link posted)

.....
if(dirs.Length > 0)
{
    foreach(string file in Directory.EnumerateFiles(dirs[0]))
    {
        .... process each file found ...
    }
}

Upvotes: 3

Grappachu
Grappachu

Reputation: 1344

Use Path.Combine() instead of string concatenation.

Upvotes: 1

Related Questions