Search code examples
linuxshellmonorm

How can Mono remove files matching a regex


As part of a project, the Mono program has to write a series of images to a movie. Therefore the images are first cached in the /tmp/ folder/ since their is a possibility that their are still images of a previous session. I want te remove these images. Therefore I use the following commands:

Process proc = new Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "rm";
proc.StartInfo.Arguments = "/tmp/output*";
proc.Start();
proc.WaitForExit();

However when the program is executed I get the following warning: /bin/rm: cannot remove '/tmp/output*': No such file or directory..

However when I executed /bin/rm /tmp/output* in the terminal (in user mode), the command doesn't seem to have a problem recognizing the files.

Why does this command doesn't work?


Solution

  • Spawning an external process for this is terrible. Just use the standard System.IO APIs, for instance:

    foreach (var file in Directory.EnumerateFiles ("/tmp", "output*")) {
        try {
            File.Delete (file);
        } catch {
            ; // optionally report error
        }
    }
    

    You may also use the overload that takes a SearchOption argument to recursively search in subdirectories. See http://msdn.microsoft.com/en-us/library/dd383571.aspx.