Warm tip: This article is reproduced from serverfault.com, please click

Removing files from folder does not seem to be working?

发布于 2020-12-02 07:16:59

I need to remove some files that are located in a folder by running the console application. However it does not seem to be working and I am not sure what I am doing wrong here?

This is the code I am using:

string[] filePaths = Directory.GetFiles(@"% USERPROFILE %\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\");
        foreach (string filePath in filePaths)
            File.Delete(filePath);

And when running the app this is the error I am getting:

Could not find a part of the path 'C:\Users\PC\source\repos\InstallUpdate\InstallUpdate\bin\Debug\netcoreapp3.1\% USERPROFILE %\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup'.'

It seem it is using the netcoreapp3.1 as the default location?

Thanks

Questioner
Keith
Viewed
0
puko 2020-12-02 15:26:52

Try to use Environment.ExpandEnvironmentVariables

    string path = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\");
    var filesToDelete = Directory.GetFiles(path);

https://docs.microsoft.com/en-us/dotnet/api/system.environment.expandenvironmentvariables?redirectedfrom=MSDN&view=net-5.0#System_Environment_ExpandEnvironmentVariables_System_String_