简体   繁体   中英

Using command prompt to delete specific files within downloads folder

I'm trying to use the following code to delete specific files from my downloads folder -

var process = new Process();
            var startInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Normal,
                FileName = "cmd.exe",
                RedirectStandardInput = true,
                UseShellExecute = false
            };

            process.StartInfo = startInfo;
            process.Start();

            process.StandardInput.WriteLine("cd C://users/%username%/downloads");
            process.StandardInput.WriteLine("del /f Secci*");

When debugging the code - the command prompt window flashes open but then instantly closes (even though it didn't specify for it to be hidden in the code) so I'm struggling to see if it's even managing to CD into the correct directory. Currently the file(s) are not being deleted from the downloads folder either. This is part of a 'Before Test' class within our test automation project. Would be great if someone could give some suggestions on why this might not be working?

For deleting in cmd prompt. Try this

string file = "Secci*";          
Process process = new Process();
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.Start();
process.StandardInput.WriteLine("cd C://users/%username%/downloads");          
process.StandardInput.WriteLine(string.Format("del \"{0}\"", file)); 

If you are trying to use System.IO, Try this.

using System.IO;

string file = "Secci*";  
//Because "SpecialFolder" doesn't have Downloads in it, this is my workaround. There may be better ones out there.
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = path.Replace("Documents", "Downloads"); 
string[] List = Directory.GetFiles(path, file);
foreach (string f in List)
{
   File.Delete(f);
}

You can get all the files by enumerating the directory. Once you have the files that match your criteria, you can iterate over them and perform actions on them.

var dir = new DirectoryInfo("C://users/%username%/downloads");

foreach (var file in dir.EnumerateFiles("Secci*")) {
    file.Delete();
}

https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.enumeratefiles?view=netframework-4.7.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM