RekcsGaming
RekcsGaming

Reputation: 153

Could not find a part of the path in c#

I am trying to build a method which is able to write in a file the number of files in another folder. I already got it but it does not work because gives me an error:

Could not find a part of the path ' C:\Users\Administrator\Desktop...\bin\release\%USERPROFILE%\AppData\Local_logC'

This is my code:

private static int GetCountGFiles(string dirname)
{
    int fileCount = 0;
    dirname = dirname.TrimEnd(new char[] { '\\' }) + @"\";

    var fixedDirname = Environment.ExpandEnvironmentVariables(dirname);

    fileCount += System.IO.Directory.GetFiles(fixedDirname).Length;

    string[] all_subdirs = System.IO.Directory.GetDirectories(dirname);

    foreach (string dir in all_subdirs)
        fileCount += GetCountGFiles(dirname); 

    string data = string.Format("LogReg.txt");

    System.IO.Directory.CreateDirectory(filePath);
    var fileandpath = filePath + data;

    using (StreamWriter writer = File.AppendText(fileandpath))
    {
        writer.WriteLine("[" + DateTime.Now + "]" + " - " + "Nº de Records: (" + fileCount.ToString() + ")");
    }

    return fileCount;
}

And then I call the method like this :

GetCountGFiles(@"%USERPROFILE%\AppData\Local\Cargas - Amostras\_logsC\");

What should I do?

Upvotes: 4

Views: 9925

Answers (2)

DavidG
DavidG

Reputation: 118937

Methods like Directory.GetFiles and Directory.GetDirectories will not automatically figure out what the environment variables that you pass to it are. You need to do that manually with Environment.ExpandEnvironmentVariables. For example:

var fixedDirname = Environment.ExpandEnvironmentVariables(dirname);

Now you can do this:

fileCount += System.IO.Directory.GetFiles(fixedDirname).Length;

(PS No need to use ToString() on a string)

Upvotes: 6

Christian.K
Christian.K

Reputation: 49220

That "%USERPROFILE%" part is a placeholder for an environment variable. The file APIs have no idea how to handle that.

You need to use Environment.ExpandEnvironmentVariables on your input string, before passing it to Directory.GetFiles

Upvotes: 2

Related Questions