Click here to Skip to main content
Click here to Skip to main content

Using Mixed .NET Languages to Simplify Access to the Recycle Bin

, 25 Mar 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Call VB functions from C# to move files or folders to the recycle bin

Introduction

A recent project I was working on allowed users to select and delete files. I wanted to allow the user to be able to gracefully recover if the wrong file was deleted. The Windows recycle bin seemed to be the perfect solution but C# did not have a function to send deleted files to the recycle bin but Visual Basic did. The obvious answer was to call the Visual Basic routines from the C# program. The solution was to create a Visual Basic class with the required functionality and compile the class as a DLL so it could be called from C#.

Background

Both C# and Visual Basic produce assemblies containing CIL code. CIL code is a platform and CPU independent intermediate language which, at runtime, is compiled to platform and CPU specific instructions. Consequently, the two languages become the same after the compile process. In fact, all .NET languages compile to CIL code so you could call Java routines or have Visual Basic call C# functions. I will show you how to create a DLL in VB that may be called by C#.

Using the Code - The Visual Basic Class

The first task was to write the deletion routines in Visual Basic. The source shown in this article will concentrate on file deletion. The class in the demo project contains code to delete either files or directories.

The simplest version of the Visual Basic delete file function requires only the path and name of the file to be deleted. The other version of the file delete function displays dialogs to track the delete operation's progress and also allows you to request an exception be thrown if the user cancels the delete operation or some other error occurs. I wanted to provide both versions to the C# programmer.

The simplest function passes the filename variable from C# to the equivalent Visual Basic function. The Visual Basic code is:

Public Shared Sub DelFile(ByVal filename As String)
    Try
        My.Computer.FileSystem.DeleteFile(filename, _
                                          FileIO.UIOption.OnlyErrorDialogs, _
                                          FileIO.RecycleOption.SendToRecycleBin, _
                                          FileIO.UICancelOption.ThrowException)
    Catch ex As Exception
        Throw ex
    End Try
End Sub

I created all subroutines using the Shared keyword so you will not have to create an instance of the VBFileIO class to access the function calls.

The other version of the function provides several options. You may elect to see the "Confirm File Delete" dialog or only error dialogs. You may also suppress or request exceptions in the event of errors. You select between the various options using Enum values. The Visual Basic Enum definitions were not displayed by the Visual Studio's IntelliSense when typing in values for the C# functions so I added my own Enum definitions and code to transform my Enum values to the equivalent Visual Basic values. My Enum definitions are:

Enum UIDialogs    'UIDialogs determine which, if any, 
                  'user dialogs are displayed during the delete
    OnlyErrorDialogs
    AllDialogs
End Enum 'UIDialogs

'CancelOptions determine if an exception is to be thrown in the event of an error
'or the user selecting No for a delete operation
Enum CancelOptions
    ThrowException
    DoNothing
End Enum 'CancelOptions

The second variation of the delete function is:

Public Shared Sub DelFile(ByVal filename As String, _
                       ByVal uiOption As UIDialogs, _
                       ByVal cancelOption As CancelOptions)

This information must be placed in a Visual Basic project. I am using Visual Basic 2008 Express Edition and Visual C# 2008 Express Edition. In Visual Basic, select File->New Project and use the Class Library template. Specify a class name of VBFileIO. Change the name of the class from Class1.vb to Recycle.vb by right clicking on the Class1.vb entry under the Solution Explorer panel and selecting the Rename option. Add the code to the class. Your class will look like this:

Public Class Recycler
    'This class is called by C# programs to delete a file or directory by
    'moving the file or directory to the recycle bin

    'UIDialogs determine which, if any, user dialogs are displayed during the delete
    Enum UIDialogs
        OnlyErrorDialogs
        AllDialogs
    End Enum 'UIDialogs

    'CancelOptions determine if an exception is to be thrown in the event of an error
    'or the user selecting No for a delete operation
    Enum CancelOptions
        ThrowException
        DoNothing
    End Enum 'CancelOptions

    'Move a file to the recycle bin
    Public Shared Sub DelFile(ByVal filename As String)
        Try
            My.Computer.FileSystem.DeleteFile(filename, _
                                              FileIO.UIOption.OnlyErrorDialogs, _
                                              FileIO.RecycleOption.SendToRecycleBin, _
                                              FileIO.UICancelOption.ThrowException)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Shared Sub DelFile(ByVal filename As String, _
                       ByVal uiOption As UIDialogs, _
                       ByVal cancelOption As CancelOptions)
        Dim cancel As FileIO.UICancelOption
        Dim uoption As FileIO.UIOption
        Select Case cancelOption
            Case CancelOptions.ThrowException
                cancel = FileIO.UICancelOption.ThrowException
            Case CancelOptions.DoNothing
                cancel = FileIO.UICancelOption.DoNothing
        End Select
        Select Case uiOption
            Case UIDialogs.AllDialogs
                uoption = FileIO.UIOption.AllDialogs
            Case UIDialogs.OnlyErrorDialogs
                uoption = FileIO.UIOption.OnlyErrorDialogs
        End Select
        Try
            My.Computer.FileSystem.DeleteFile(filename, _
                                              uoption, _
                                              FileIO.RecycleOption.SendToRecycleBin, _
                                              cancel)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

End Class

Build the class to create a DLL file. The Visual Basic portion of the project is complete.

Using the Code - The C# Interface

Use of the Visual Basic class in C# is straight forward. Choose a project of your own or look at the code in the MixedLanguageDemo. Begin by registering the VBFileIO.dll by right clicking the References tab in the Solution Explorer panel for the C# project. Select "Add Reference" and choose the Browse tab. Navigate to the bin.Release folder contained in the VBFileIO project created above and select VBFileIO.dll. The DLL is now registered as a referenced external assembly. You do not need to copy the DLL to the C# project folder. Visual Studio will automatically copy the DLL to the appropriate target folders when the C# project is built.

Add using VBFileIO; to the using list In your C# program. One, the statement clearly documents the program is using the VBFileIO interface. Two, it saves key strokes when programming.

You may now delete a file using either of the following functions:

Recycler.DelFile(fileName);
Recycler.DelFile
    (fileName, Recycler.UIDialogs.AllDialogs, Recycler.CancelOptions.ThrowException);

Directories may be deleted with either of the following functions:

Recycler.DelDir(dirName);
Recycler.DelDir
    (dirName, Recycler.UIDialogs.AllDialogs, Recycler.CancelOptions.ThrowException);

Points of Interest

Use try/catch logic when calling DelFile from C# to determine if the user cancelled the delete via the dialog or if an error occurred. I also noticed Read Only files are deleted without a warning.

History

  • 21st March, 2008: Version 1.0.0.0 (It has been tested on Windows XP and Vista.)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Roger500
Software Developer (Senior) retired
United States United States
No Biography provided

Comments and Discussions

 
GeneralAnother warning PinmemberRichard Deeming3-Apr-08 2:51 
GeneralRe: Another warning PinmemberRoger5003-Apr-08 9:43 
GeneralBe careful PinmemberPIEBALDconsult25-Mar-08 20:34 
I don't like the recycler so I turn it off.
But at least one HP product I have throws an unhandled exception when I try to delete a file with it.
Test your technique with the recycler disabled and see what happens.
GeneralRe: Be careful PinmemberRoger50026-Mar-08 8:17 
GeneralRe: Be careful PinmemberPIEBALDconsult26-Mar-08 15:26 
GeneralRe: Be careful PinmemberRoger50026-Mar-08 17:32 
GeneralRe: Be careful PinmemberPIEBALDconsult27-Mar-08 11:50 
GeneralRe: Can use pure C# PinmemberRoger50025-Mar-08 17:54 
GeneralRe: Can use pure C# PinmemberRavi Bhavnani25-Mar-08 18:22 
GeneralRe: Can use pure C# PinmemberRoger50026-Mar-08 8:06 
AnswerRe: Can use pure C# PinmemberRavi Bhavnani26-Mar-08 13:44 
GeneralRe: Can use pure C# PinmemberRoger50026-Mar-08 17:22 
GeneralRe: Can use pure C# PinmemberPIEBALDconsult25-Mar-08 20:35 
GeneralRe: Can use pure C# PinmemberRoger50026-Mar-08 8:13 
GeneralRe: Can use pure C# PinmemberPIEBALDconsult26-Mar-08 15:24 
GeneralRe: Can use pure C# PinmemberAlberto Venditti8-Apr-08 3:39 
QuestionCan use pure C# PinmemberK Robertson25-Mar-08 15:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411022.1 | Last Updated 25 Mar 2008
Article Copyright 2008 by Roger500
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid