Skip to content

How to copy a file using windows service in c#

praveen kumar

Asked Jan 29, 2015, 1:54 AM EST2 answers
Share
LinkedInX
I want to copy a file from one location to other location using windows service between time interval, help me to get out of the issue

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Pranay Rana
    0
    You can do is

    1. Create System.Timer object which will intiate your file transfer
    2. In elapse method of timer create asncy task with the cancellation token in which specify amount of time in second transfer operation should complete

    I hope by doing this problem will get resolve.
    0
  • 0
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.IO;
    using System.Timers;

    namespace ws
    {
        public partial class ScheduledService : ServiceBase
        {
           
            Timer timer = new Timer();
            public ScheduledService()
            {
                InitializeComponent();
            }

               
           
            protected override void OnStart(string[] args)
            {
              
                TraceService("start service");

             
                timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

          
                timer.Interval = 60000;

            
                timer.Enabled = true;
            }

            protected override void OnStop()
            {
                timer.Enabled = false;
                TraceService("stopping service");
            }
            private void OnElapsedTime(object source, ElapsedEventArgs e)
            {
                TraceService("File Backup at " + DateTime.Now);
            }
            private void TraceService(string content)
            {
             
                FileStream fs = new FileStream(@"d:\ScheduledService.txt",FileMode.OpenOrCreate, FileAccess.Write);

          
                StreamWriter sw = new StreamWriter(fs);

               
                sw.BaseStream.Seek(0, SeekOrigin.End);

            
                sw.WriteLine(content);
            

                sw.Flush();
                sw.Close();

            }
        }
    }



    This is my program, in this where to use file.copy
    0