1.如何监视目录using System;
using System.IO;
namespace Watcher
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Watcher
{ public static void Main()
{ string[] args = System.Environment.GetCommandLineArgs();
 
// If a directory is not specified, exit program.
if(args.Length != 2)
{
// Display the proper way to call the program.
Console.WriteLine("Usage: Watcher.exe (directory)");
return;
} // Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = args[1];
/* Watch for changes in LastAccess and LastWrite times, and 
   the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt"; // Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed); // Begin watching.
watcher.EnableRaisingEvents = true; // Wait for the user to quit the program.
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
} // Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
} private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
}}

解决方案 »

  1.   

    2.怎么用程序重新启动一系列的Windows Services? 
             ServiceController sc  = new ServiceController();
             sc.ServiceName = "Alerter";
             Console.WriteLine("The Alerter service status is currently set to {0}", 
                                sc.Status.ToString());         if (sc.Status == ServiceControllerStatus.Stopped)
             {
                // Start the service if the current status is stopped.            Console.WriteLine("Starting the Alerter service...");
                try 
                {
                   // Start the service, and wait until its status is "Running".
                   sc.Start();
                   sc.WaitForStatus(ServiceControllerStatus.Running);
                
                   // Display the current service status.
                   Console.WriteLine("The Alerter service status is now set to {0}.", 
                                      sc.Status.ToString());
                }
                catch (InvalidOperationException)
                {
                   Console.WriteLine("Could not start the Alerter service.");
                }
             }
    3.windows service程序创建后生成成功了,如何安装
    在.Net中用C#创建Windows Service,其实很简单,按照以下的步骤就可以做出一个简单的Windows Service。
    1.首先在创建工程的时候选择Windows Service,这样.Net会自动生成Windows Service的框架;
    2.完成Windows Service的相应事件,主要是OnStart和OnStop这两个事件,完成后大致代码如下:
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.ServiceProcess;
    using System.IO;
    using System.Threading;
    namespace WinSDemo
    {
        public class WinSDemo : System.ServiceProcess.ServiceBase
        {        /// <summary> 
            /// Required designer variable.
           /// </summary>        private System.ComponentModel.Container components = null;        private bool blnStopThread;        private Thread thdMain;         public WinSDemo()        {            // This call is required by the Windows.Forms Component Designer.            InitializeComponent();             // TODO: Add any initialization after the InitComponent call        }         // The main entry point for the process        static void Main()        {            System.ServiceProcess.ServiceBase[] ServicesToRun;                // More than one user Service may run within the same process. To add            // another service to this process, change the following line to            // create a second service object. For example,            //            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinSDemo() };             System.ServiceProcess.ServiceBase.Run(ServicesToRun);        }         /// <summary>         /// Required method for Designer support - do not modify         /// the contents of this method with the code editor.        /// </summary>        private void InitializeComponent()        {            //             // WinSDemo            //             this.CanPauseAndContinue = true;            this.ServiceName = "MyTest";         }         /// <summary>        /// Clean up any resources being used.        /// </summary>        protected override void Dispose( bool disposing )        {            if( disposing )            {                if (components != null)                 {                    components.Dispose();                }            }            base.Dispose( disposing );        }         /// <summary>        /// Set things in motion so your service can do its work.        /// </summary>        protected override void OnStart(string[] args)        {            // TODO: Add code here to start your service.             thdMain=new Thread(new ThreadStart(WriteLog));            thdMain.Start();        }         /// <summary>        /// Stop this service.        /// </summary>        protected override void OnStop()        {            // TODO: Add code here to perform any tear-down necessary to stop your service.            blnStopThread=true;            thdMain.Join();        }         protected override void OnPause()        {            thdMain.Suspend();        }         protected override void OnContinue()        {            thdMain.Resume();        }         protected void WriteLog()        {            StreamWriter myWriter=null;                     do            {                Process.Start("net","send localhost yourValue");                try                {                    myWriter=new StreamWriter("c:\\MyLog.txt",true);                    myWriter.WriteLine(DateTime.Now.ToString());                    myWriter.Close();                }                catch{};                 Thread.Sleep(5000);            }while(blnStopThread==false);                    }    }}       注:为了使自己能更好的识别自己写的Windows Service,建议在InitializeComponent修改Service的名称。 3.为了使自己写的Service能加载到系统中去,光靠以上步骤是不够;接下来,向当前的工程添加Service Installer,在其中设置Service安装后的起始状态,代码如下:using System;using System.Collections;using System.ComponentModel;using System.Configuration.Install;using System.ServiceProcess;  namespace WinSDemo{    /// <summary>    /// Summary description for WinSDemoIns.    /// </summary>    [RunInstaller(true)]    public class WinSDemoIns : System.Configuration.Install.Installer    {        /// <summary>        /// Required designer variable.        /// </summary>        private System.ComponentModel.Container components = null;        private ServiceInstaller serviceInstaller;        private ServiceProcessInstaller processInstaller;         public WinSDemoIns()        {            // This call is required by the Designer.            InitializeComponent();             // TODO: Add any initialization after the InitComponent call            processInstaller = new ServiceProcessInstaller();            serviceInstaller = new ServiceInstaller();             // Service will run under system account            processInstaller.Account = ServiceAccount.LocalSystem;             // Service will have Start Type of Manual            serviceInstaller.StartType = ServiceStartMode.Automatic;             serviceInstaller.ServiceName = "MyTest";             Installers.Add(serviceInstaller);            Installers.Add(processInstaller);        }         #region Component Designer generated code        /// <summary>        /// Required method for Designer support - do not modify        /// the contents of this method with the code editor.        /// </summary>        private void InitializeComponent()        {            components = new System.ComponentModel.Container();        }        #endregion    }} 4.完成以上的步骤,代码的部分就完成了,编译成可执行文件,再用.Net的Service安装工具就行了,即在Dos窗口中,键入“installutil yourService.exe”,这样执行就可以了,相反,如果想卸载Service的话,加一个参数就可以了,即“installutil /u yourService.exe”。注意有可能.Net的路径在环境变量中不存在,可能直接执行是不能成功的,希望先找到“installutil.exe”存在的目录,大致在“\WINDOWS\Microsoft.NET\Framework\v1.1.4322”目录下。 至于以后Service的部署,由于.Net写的程序,运行环境必须要安装.Net Framework,所以在其他机器安装自己写的Service时候,一定要先安装.Net运行环境。
      

  2.   

    四 :MSDN中的安装实例using System;
    using System.Collections;
    using System.Configuration.Install;
    using System.ServiceProcess;
    using System.ComponentModel;[RunInstallerAttribute(true)]
    public class MyProjectInstaller: Installer{
       private ServiceInstaller serviceInstaller1;
       private ServiceInstaller serviceInstaller2;
       private ServiceProcessInstaller processInstaller;   public MyProjectInstaller(){
          // Instantiate installers for process and services.
          processInstaller = new ServiceProcessInstaller();
          serviceInstaller1 = new ServiceInstaller();
          serviceInstaller2 = new ServiceInstaller();      // The services run under the system account.
          processInstaller.Account = ServiceAccount.LocalSystem;      // The services are started manually.
          serviceInstaller1.StartType = ServiceStartMode.Manual;
          serviceInstaller2.StartType = ServiceStartMode.Manual;      // ServiceName must equal those on ServiceBase derived classes.            
          serviceInstaller1.ServiceName = "Hello-World Service 1";
          serviceInstaller2.ServiceName = "Hello-World Service 2";      // Add installers to collection. Order is not important.
          Installers.Add(serviceInstaller1);
          Installers.Add(serviceInstaller2);
          Installers.Add(processInstaller);
       }
    }
      

  3.   

    五:定时处理任务
    using System.Timers;protected Timer _updaterTimer;
    _updaterTimer = new Timer();
    _updaterTimer.Interval = 1000; //1秒钟
    _updaterTimer.Enabled = true;
    _updaterTimer.Elapsed += new ElapsedEventHandler(OnTimer);protected void OnTimer(Object source, ElapsedEventArgs e)
    {
    ...
    }或者用THREAD
    using System;
    using System.Threading;// Simple threading scenario:  Start a static method running
    // on a second thread.
    public class ThreadExample {
        // The ThreadProc method is called when the thread starts.
        // It loops ten times, writing to the console and yielding 
        // the rest of its time slice each time, and then ends.
        public static void ThreadProc() {
            for (int i = 0; i < 10; i++) {
                Console.WriteLine("ThreadProc: {0}", i);
                // Yield the rest of the time slice.
                Thread.Sleep(0);
            }
        }    public static void Main() {
            Console.WriteLine("Main thread: Start a second thread.");
            // The constructor for the Thread class requires a ThreadStart 
            // delegate that represents the method to be executed on the 
            // thread.  C# simplifies the creation of this delegate.
            Thread t = new Thread(new ThreadStart(ThreadProc));
            // Start ThreadProc.  On a uniprocessor, the thread does not get 
            // any processor time until the main thread yields.  Uncomment 
            // the Thread.Sleep that follows t.Start() to see the difference.
            t.Start();
            //Thread.Sleep(0);        for (int i = 0; i < 4; i++) {
                Console.WriteLine("Main thread: Do some work.");
                Thread.Sleep(0);
            }        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
            t.Join();
            Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.");
            Console.ReadLine();
        }
    }
      

  4.   

    六:文件上传
    Console.Write("\nPlease enter the URL to post data to : ");
    String uriString = Console.ReadLine();// Create a new WebClient instance.
    WebClient myWebClient = new WebClient();Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URL");
    string fileName = Console.ReadLine();Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);                        
    // Upload the file to the URL using the HTTP 1.0 POST.
    byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);// Decode and display the response.
    Console.WriteLine("\nResponse Received.The contents of the file uploaded are: \n{0}",Encoding.ASCII.GetString(responseArray));
    -----------------------------------------------------
    [C#] 
    <%@ Import Namespace="System"%>
    <%@ Import Namespace="System.IO"%>
    <%@ Import Namespace="System.Net"%>
    <%@ Import NameSpace="System.Web"%><Script language="C#" runat=server>
    void Page_Load(object sender, EventArgs e) {
        
        foreach(string f in Request.Files.AllKeys) {
            HttpPostedFile file = Request.Files[f];
            file.SaveAs("c:\\inetpub\\test\\UploadedFiles\\" + file.FileName);
        }    
    }</Script>
    <html>
    <body>
    <p> Upload complete.  </p>
    </body>
    </html>
    七:文件下载
    string remoteUri = "http://www.contoso.com/library/homepage/images/";
    string fileName = "ms-banner.gif", myStringWebResource = null;
    // Create a new WebClient instance.
    WebClient myWebClient = new WebClient();
    // Concatenate the domain with the Web resource filename.
    myStringWebResource = remoteUri + fileName;
    Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
    // Download the Web resource and save it into the current filesystem folder.
    myWebClient.DownloadFile(myStringWebResource,fileName);        
    Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
    Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath);