Microsoft KB Archive/829483

= 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 ID: 829483

Article Last Modified on 4/19/2007

-

APPLIES TO


 * Microsoft Visual C++ 2005 Express Edition
 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft .NET Framework 1.1

-





This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System::IO
 * System::Collections
 * System::ServiceProcess
 * System::ComponentModel
 * System::Configuration::Install

IN THIS TASK

 * SUMMARY
 * Requirements
 * Create a Windows Service project
 * Install the Windows Service
 * Start the Windows Service
 * Verify that the application works
 * Troubleshooting
 * REFERENCES



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.

Back to the top

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.

Back to the top

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

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

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

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

The FileHandlingWinService Windows Service is created and is opened in Design mode. Add a Timer control to the Service Designer window. Right-click timer1, and then click Properties.</li> In the Properties window, change the Enabled property to False.</li> 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.</li>  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; </li>  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; </li>  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&quot;&quot;; //Set the timer interval, enable the timer, and start the timer. timer1->Interval = 20000; timer1->Enabled = true; timer1->Start; } return; </li>  Add the following code in the OnStop function inside the FileHandlingWinService class definition: // Stop the timer. timer1->Stop; </li>  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&quot;The directory was created successfully at {0}.&quot;, __box(Directory::GetCreationTime(path))); }       else {           Console::WriteLine(S&quot;That path already exists.&quot;); }   }     catch (Exception* e)     { Console::WriteLine(S&quot;The process failed: {0}&quot;, 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&quot;The number of files ending with XLS is {0}.&quot;, __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&quot;move&quot;,true)==0) {               // Move the file. File::Move(SourceFilePath, TargetFilePath); }           else if (String::Compare(MoveCopyParam ,S&quot;delete&quot;,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&quot;The process failed: {0}&quot;, 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: <ol style="list-style-type: lower-alpha;"> Click Project, and then click  Properties.

Note  is a placeholder for the name of the project.</li> Expand Configuration Properties, and then click General.</li> 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.</li></ol>

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

</li> Switch to Designer view.</li> Right-click anywhere in Designer view, and then click Properties.</li> 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.</li> In Designer view, right-click ServiceProcessInstaller1, and then click Properties.</li> In the Properties window, change the Account property to LocalSystem.</li> <li>Press CTRL+SHIFT+B to build the project.</li></ol>

Back to the top

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.
 * 1) 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.
 * 2) At the command prompt, type   -install, and then press ENTER.

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

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

Back to the top

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.
 * 1) Locate FileHandlingWinService in the list of installed services.
 * 2) Right-click FileHandlingWinService, and then click Properties.
 * 3) In the Start parameters text box, type the following start-up parameters for the Windows Service: &quot; :\\ \\&quot; &quot; :\\ \\&quot; &quot;*.TXT&quot; &quot;move&quot;.

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

Note, ,  , and   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.
 * 1) Click Start.

Back to the top

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.
 * 1) Locate the destination directory.

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

Back to the top

Troubleshooting
You can use the following resources if you require help: <ul> <li>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.

</li> <li>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

</li> <li>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.</li></ul>

Back to the top

Additional query words: Copy Delete Move File Directory CreateDirectory Timer Windows Service Elapsed ServiceInstaller Copy Delete and move files using Wildcard Character

<div class="references_section">