How to move, to delete, or to copy files by using a wildcard character in a Windows Service with Visual C++ .NET or Visual C++ 2005

Article translations Article translations
Article ID: 829483 - View products that this article applies to.
Expand all | Collapse all

On This Page

SUMMARY

This article describes how to create a Windows Service project with Microsoft Visual C++ .NET 2003 or Microsoft Visual C++ 2005 and then how to install the Windows Service. This article also describes how to provide the Windows Service start-up parameters for a Windows Service and then start the Windows Service.

This article also describes how to move, to copy, or to delete files from a directory according to the Windows Service start-up parameters by using the Timer control.


Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows XP Professional, Microsoft Windows XP Server, or Microsoft Windows Server 2003 with the Microsoft .NET Framework 1.1
  • Microsoft Visual Studio .NET 2003 Enterprise Edition or Microsoft Visual Studio .NET 2003 Enterprise Architect
This article assumes that you are familiar with the following topics:
  • Windows Service
  • Timers
This article also assumes that the user account that you use has the permissions that you must have to install the Windows Service and to start the Windows Service.


Create a Windows Service project

To create a Windows Service project with Visual C++ .NET 2003 or Visual C++ 2005, follow these steps:
  1. Start Visual Studio .NET 2003 or Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.

    The New Project dialog box appears.
  3. Under Project Types, click Visual C++ Projects.

    Note In Visual Studio 2005, click Visual C++ under Project Types.
  4. Under Templates, click Windows Service (.NET).

    Note In Visual Studio 2005, click Windows Service under Templates.
  5. In the Name text box, type FileHandling, and then click OK.

    The FileHandlingWinService Windows Service is created and is opened in Design mode.
  6. Add a Timer control to the Service Designer window.
  7. Right-click timer1, and then click Properties.
  8. In the Properties window, change the Enabled property to False.
  9. Double-click timer1 in the Service Designer window to view the Code window.

    This creates a timer1_Elapsed event and then puts the pointer in the first line of the code of the event handler.
  10. Add the following code inside the FileHandlingWinService class definition before the constructor:
    public:
            //Declare variables to hold the Windows Service start-up parameter values.
            String * FromDirectory;
            String * ToDirectory;
            String * WildCard;
            String * MoveCopyParam;
  11. The file manipulation classes and the directory manipulation classes reside in the System::IO namespace. To refer to the System::IO namespace, add the following line of code at the top of the Code window after the using statements:
    using namespace System::IO;
  12. Add the following code in the OnStart() function inside the FileHandlingWinService class definition:
    //Verify the number of arguments.
    Int32 i = args->Length;
    if (i >= 3)
    {
    	//Copy the Windows Service start-up arguments to the class variables.
        FromDirectory = (args[0]);
        ToDirectory = (args[1]);
        WildCard = (args[2]);
        //Copy the optional parameter.
        if (i == 4)
    		MoveCopyParam = (args[3]);
    	else
    		MoveCopyParam = S"";
        
        //Set the timer interval, enable the timer, and start the timer.
        timer1->Interval = 20000;
        timer1->Enabled = true;
        timer1->Start(); 
    }
    return;
  13. Add the following code in the OnStop() function inside the FileHandlingWinService class definition:
    // Stop the timer.
    timer1->Stop();
  14. Add the following code in the timer1_Elapsed event handler:
    // Verify the Windows Service start-up parameter values.
    if ( FromDirectory->Length !=0  && ToDirectory->Length !=0 && WildCard->Length !=0)
    {
        // Copy the destination (target) directory to a variable.
        String* path = ToDirectory ;
        try 
        {
            // Determine whether the destination directory exists.
            if (!Directory::Exists(path)) 
            {
                // Try to create the directory.
                DirectoryInfo* di = Directory::CreateDirectory(path);
                Console::WriteLine(S"The directory was created successfully at {0}.", __box(Directory::GetCreationTime(path)));
            }
            else
            {
                Console::WriteLine(S"That path already exists.");
            }
        } 
        catch (Exception* e) 
        {
            Console::WriteLine(S"The process failed: {0}", e);
        }
    
        // Create a reference to the source directory.
        try 
        {
            // Only get files that match the wildcard character pattern.
            String* dirs[] = Directory::GetFiles(FromDirectory, WildCard);
            Console::WriteLine(S"The number of files ending with XLS is {0}.", __box(dirs->Length));
            // Iterate through the file collection.
            Collections::IEnumerator* myEnum = dirs->GetEnumerator();
            while (myEnum->MoveNext()) 
            {
                // Get the source file path and the destination file path.
                String * SourceFilePath = static_cast<String *>(myEnum->Current);
                String * TargetFilePath = String::Concat(ToDirectory ,Path::GetFileName(SourceFilePath));
                
                // Compare the optional (fourth) start-up parameter value.
                if (String::Compare(MoveCopyParam ,S"move",true)==0)
                {
                    // Move the file.
                    File::Move(SourceFilePath, TargetFilePath);
                }
                else if (String::Compare(MoveCopyParam ,S"delete",true)==0)
                {
                    // Delete the file.
                    File::Delete(SourceFilePath);
                }
                else 
                {
                    // Copy the file and then overwrite the file if the file already exists.
                    File::Copy(SourceFilePath, TargetFilePath, true);
                }
            }
        } 
        catch (Exception* e) 
        {
            Console::WriteLine(S"The process failed: {0}", e);
        }
    }
    Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps:
    1. Click Project, and then click <ProjectName> Properties.

      Note <ProjectName> is a placeholder for the name of the project.
    2. Expand Configuration Properties, and then click General.
    3. Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.
    For more information about the common language runtime support compiler option, visit the following Microsoft Web site:
    /clr (Common Language Runtime Compilation)
    http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx
  15. Switch to Designer view.
  16. Right-click anywhere in Designer view, and then click Properties.
  17. In the Properties window, click the Add Installer link.

    This creates a new ProjectInstaller class with ServiceInstaller class variables and with ServiceProcessInstaller class variables. The ProjectInstaller is opened in Designer view.
  18. In Designer view, right-click ServiceProcessInstaller1, and then click Properties.
  19. In the Properties window, change the Account property to LocalSystem.
  20. Press CTRL+SHIFT+B to build the project.

Install the Windows Service

In Visual Basic .NET and in Visual C# .NET you must create a Setup project to install a Windows Service. However, Visual C++ .NET Windows Service executables do not require a Setup project to install a Windows Service. You cannot run the installutil utility directly on the Visual C++ .NET Windows Service executable. The Windows Service executable has built-in installation functionality. To invoke this functionality, run the executable with the -install switch. Make sure that you add the .exe extension when you use this switch.

To install the Windows Service, follow these steps:
  1. Click Start, and then click Run.
  2. In the Open box, type cmd, and then click OK.

    This opens the command prompt.
  3. At the command prompt, locate the directory where you created the Windows Service project, and then locate the Debug directory under the directory where you created the Windows Service project.
  4. At the command prompt, type Windows Service Executable File -install, and then press ENTER.

    The Windows Service that you created is installed on your computer.

    Note Windows Service Executable File is the placeholder for the name of the Windows Service executable file that you created.

Start the Windows Service

After you create the Windows Service and then you install the Windows Service, you must provide start-up parameters to start the Windows Service.

The Windows Service you previously created requires three start-up parameters to run successfully. The required start-up parameters are:
  • Source files directory path
  • Destination (target) directory Path
  • Wildcard character search pattern
There is an optional fourth start-up parameter that you may provide. This optional start-up parameter defines the operation that you want the Windows Service to perform. The operations are move, delete, or copy. Copy is the default operation.

To start the Windows Service, follow these steps:
  1. In Control Panel, double-click Administrative Tools, and then double-click Services.

    This opens the Services window.
  2. Locate FileHandlingWinService in the list of installed services.
  3. Right-click FileHandlingWinService, and then click Properties.
  4. In the Start parameters text box, type the following start-up parameters for the Windows Service: "Source Drive Letter:\\YourSourceDirectory\\" "Destination Drive Letter:\\YourDestinationDirectory\\" "*.TXT" "move".

    This command moves a set of files from one folder to another folder.

    Note Source Drive Letter, YourSourceDirectory, Destination Drive Letter, and YourDestinationDirectory are the placeholders for the Source file drive letter, the Source file path in UNC format, the destination file drive letter, and the destination file path in UNC format, respectively.
  5. Click Start.

Verify that the application works

  1. Copy some text files in your source directory before you start the Windows Service.
  2. Start the Windows Service. Specify the correct start-up parameters.
  3. Wait 20 seconds.

    Twenty seconds is the Timer control interval that you specified.
  4. Locate the destination directory.

    Notice that the text files that you copied are listed in the destination directory.
  5. Copy other text files in the source directory. Verify whether these text files are copied to the destination directory after the Timer control interval.

Troubleshooting

You can use the following resources if you require help:
  • For additional information, see The Microsoft .NET Framework Software Development Kit (SDK) documentation

    Note The .NET Framework SDK states the following:
    The compiled executable file that a service application project creates must be installed on the server before the project can function in a meaningful way. You cannot debug or run a service application by pressing F5 or F11; you cannot immediately run a service or step into its code. Instead, you must install and start your service, and then attach a debugger to the service's process.
  • For additional information about debugging Windows Service applications, visit the following Microsoft Developer Network (MSDN) Web site:
    http://msdn2.microsoft.com/en-us/library/aa984342(VS.71).aspx
  • For additional information about why you must use the Timer control, click the following article number to view the article in the Microsoft Knowledge Base:
    820639 PRB: Microsoft Windows forms Timer event is not raised in a Windows Service
    Make sure that you use the Timer control that you moved from the Components tab of the Toolbox.

REFERENCES

For additional information about the Directory class, visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/system.io.directory(vs.71).aspx
For additional information about the File class, visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/system.io.file(vs.71).aspx

Properties

Article ID: 829483 - Last Review: April 19, 2007 - Revision: 2.4
APPLIES TO
  • Microsoft Visual C++ 2005 Express Edition
  • Microsoft Visual C++ .NET 2003 Standard Edition
  • Microsoft .NET Framework 1.1
Keywords: 
kbwinservsetup kbtimer kbserviceprocess kbservice kbfilesystems kbfileio kbdirectory kbdir kbcollections kbhowtomaster KB829483

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com