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 (829483)
The information in this article applies to:
- Microsoft Visual C++ 2005 Express Edition
- Microsoft Visual C++ .NET (2003)
- 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 TASKSUMMARYThis
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 topRequirementsThe
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:
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 topCreate a Windows Service projectTo 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.
- In the Properties window, change the
Enabled property to False.
- 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. - 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; - 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; - 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; - Add the following code in the OnStop()
function inside the FileHandlingWinService class definition:
// Stop the timer.
timer1->Stop(); - 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:
- Click Project, and then click <ProjectName> Properties.
Note <ProjectName> is a placeholder for the name of the project. - Expand Configuration Properties, and then click General.
- 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: - Switch to Designer view.
- Right-click anywhere in Designer view, and then click
Properties.
- 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. - In Designer view, right-click
ServiceProcessInstaller1, and then click
Properties.
- In the Properties window, change the
Account property to LocalSystem.
- Press CTRL+SHIFT+B to build the
project.
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:
- Click Start, and then
click Run.
- In the Open box, type cmd, and then click
OK.
This opens the command prompt. - 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.
- 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. 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:
- In Control Panel, double-click Administrative
Tools, and then double-click Services.
This
opens the Services window. - Locate FileHandlingWinService in the list
of installed services.
- Right-click FileHandlingWinService,
and then click Properties.
- 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. - Click Start.
Back to the top Verify that the application works- Copy some text files in your source directory before
you start the Windows Service.
- Start the Windows Service. Specify the correct
start-up parameters.
- Wait 20 seconds.
Twenty seconds is the Timer control interval that you
specified. - Locate the destination directory.
Notice that the text files that you copied are listed
in the destination directory. - 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 topTroubleshootingYou 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:
-
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. Back to the topREFERENCESFor additional information about the Directory
class, visit the following MSDN Web site: For additional information about the File
class, visit the following MSDN Web site: Back
to the top
Modification Type: | Major | Last Reviewed: | 12/31/2005 |
---|
Keywords: | kbwinservsetup kbTimer kbServiceProcess kbService kbFileSystems kbFileIO kbDirectory kbdir kbCollections kbHOWTOmaster KB829483 kbAudDeveloper |
---|
|
|
©2004 Microsoft Corporation. All rights reserved.
|
|