5

I have been able to delete files permanently with below code:

var DeleteFromDir = new DirectoryInfo(sFromPath);
var files = DeleteFromDir.GetFiles(".txt");
foreach(var file in files)
{
    if(bDeletePermanently)
        file.Delete();
    else
        ; //Move to recycle bin
}

I tried below :

Add a reference to Microsoft.VisualBasic assembly. The needed class is found in this library.

  • Add this using statement to the top of the file using Microsoft.VisualBasic.FileIO;

  • Use FileSystem.DeleteFile to delete a file, it has the option to specify recycle bin or not.

But this works only with UI context and my application is Console based.

3
  • 1
    You could put the [STAThread] attribute on your Main() method. It is a pretty gross violation of apartment state rules but you'll get away with it, lots of VB.NET programs do. If your program deadlocks then you didn't. Commented Aug 2, 2016 at 8:33
  • @HansPassant, I thought it's used for threads.. didn't know we could use it for Console too.. Can you please write sample code, if it helps solving the problem I'm facing? Commented Aug 3, 2016 at 13:00
  • It certainly matters to threads. If you create any and they use an apartment-threaded COM server then you'll nurse deadlock. Rather low odds for that. The method you are using in turns uses SHFileOperation(). A winapi function that demands STA because it might display a user interface. It won't when you delete to the recycle bin so nothing to worry about there. No idea how to turn 9 characters for [STAThread] into sample code. Just use it. Commented Aug 3, 2016 at 13:11

1 Answer 1

0

If you have a reference to the Microsoft.VisualBasic assembly (there is also a NuGet package for this if you prefer), then you should be able to use the code below.

var DeleteFromDir = new DirectoryInfo(sFromPath);
var files = DeleteFromDir.GetFiles("*.txt");
foreach (var file in files)
{
    if (bDeletePermanently)
    {
        file.Delete();
    }
    else
    {
        FileSystem.DeleteFile(file.FullName, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
    }
}

In response to your concern about the UI context, the function will only "show error dialog boxes and hide progress dialog boxes". I found this on Microsoft's docs if you want to read further.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.