Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not find a part of the path in c#

Tags:

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?

like image 464
RekcsGaming Avatar asked Oct 22 '25 02:10

RekcsGaming


1 Answers

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)

like image 75
DavidG Avatar answered Oct 24 '25 17:10

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!