Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
Firstly sorry i was not able to update the question as I didn't had access to  network connection.@Richard and @Sunasara
 
I need to download the data from a particular server say for example //192.16.124.30 to my below directories using windows service so that whenever the service runs it will delete old data and download new data by itself. i have a service which does this by a batch file but its taking a lot of time so i have m trying to do this by ftp! 

c:\webdata\jhstock 
C:\webdata\mistar


below is my code of win service and the example code found on code projects Simple c# FTP class

this is the code i found on code project's site

<pre>class ftp
{
    private string host = null;
    private string user = null;
    private string pass = null;
    private FtpWebRequest ftpRequest = null;
    private FtpWebResponse ftpResponse = null;
    private Stream ftpStream = null;
    private int bufferSize = 2048;
        
    /* Construct Object */
    public ftp(string hostIP, string userName, string password) { host = hostIP; user = userName; pass = password; }

    /* Download File */
    public void download(string remoteFile, string localFile)
    {
        try
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
            /* Log in to the FTP Server with the User Name and Password Provided */
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            /* When in doubt, use these options */
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            /* Specify the Type of FTP Request */
            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            /* Establish Return Communication with the FTP Server */
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            /* Get the FTP Server's Response Stream */
            ftpStream = ftpResponse.GetResponseStream();
            /* Open a File Stream to Write the Downloaded File */
            FileStream localFileStream = new FileStream(localFile, FileMode.Create);
            /* Buffer for the Downloaded Data */
            byte[] byteBuffer = new byte[bufferSize];
            int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
            /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
            try
            {
                while (bytesRead > 0)
                {
                    localFileStream.Write(byteBuffer, 0, bytesRead);
                    bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                }
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            /* Resource Cleanup */
            localFileStream.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        return;
    }



My win service

Service1.cs
public partial class Service1 : ServiceBase
    {
        private Timer timer1 = null;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new Timer();
            this.timer1.Interval = 60000; //60 sec
            this.timer1.Elapsed +=new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled=true;
            Library.WriteErrorLog("test windows service started");
            var result = RunProcess(@"D:\Webdata", "cmd.exe", "D:\\Webdata\\Copy_All.bat", false);
                                   
            if (result == 0)
            {
                // success
                Console.WriteLine("Sucess");
            }
            else
            {
                // failed ErrorLevel / app ExitCode
                Console.WriteLine("failed try again");

            }
            
            
        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
            Library.WriteErrorLog("Test Service ended");
        }



Program.cs

static void Main(String[] args)
      {
          // Initialize the service to start
          ServiceBase[] ServicesToRun;
          ServicesToRun = new ServiceBase[]
  {
      new Service1()
  };

          // In interactive mode ?
          if (Environment.UserInteractive)
          {
              // In debug mode ?
              if (System.Diagnostics.Debugger.IsAttached)
              {
                  // Simulate the services execution
                  RunInteractiveServices(ServicesToRun);
              }
              else
              {
                  try
                  {
                      bool hasCommands = false;
                      // Having an install command ?
                      if (HasCommand(args, "install"))
                      {
                          ManagedInstallerClass.InstallHelper(new String[] { typeof(Program).Assembly.Location });
                          hasCommands = true;
                          // Having a start command ?
                          if (HasCommand(args, "start"))
                          {
                              foreach (var service in ServicesToRun)
                              {
                                  ServiceController sc = new ServiceController(service.ServiceName);
                                  sc.Start();
                                  sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
                              }
                              hasCommands = true;
                          }
                      }
                      // Having a stop command ?
                      if (HasCommand(args, "stop"))
                      {
                          foreach (var service in ServicesToRun)
                          {
                              ServiceController sc = new ServiceController(service.ServiceName);
                              sc.Stop();
                              sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10000));// change
                          }
                          hasCommands = false;
                      }
                      // Having an uninstall command ?
                      if (HasCommand(args, "uninstall"))
                      {
                          ManagedInstallerClass.InstallHelper(new String[] { "/u", typeof(Program).Assembly.Location });
                          hasCommands = true;


                      }
                      // If we don't have commands we print usage message
                      if (!hasCommands)
                      {
                          Console.WriteLine("Usage : {0} [command] [command ...]", Environment.GetCommandLineArgs());
                          Console.WriteLine("Commands : ");
                          Console.WriteLine(" - install : Install the services");
                          Console.WriteLine(" - uninstall : Uninstall the services");
                      }
                  }
                  catch (Exception ex)
                  {
                      var oldColor = Console.ForegroundColor;
                      Console.ForegroundColor = ConsoleColor.Red;
                      Console.WriteLine("Error : {0}", ex.GetBaseException().Message);
                      Console.ForegroundColor = oldColor;
                  }
              }
          }
          else
          {
              // Normal service execution
              ServiceBase.Run(ServicesToRun);
          }
      }

      static void RunInteractiveServices(ServiceBase[] servicesToRun)
      {
          Console.WriteLine();
          Console.WriteLine("Start the services in interactive mode.");
          Console.WriteLine();

          // Get the method to invoke on each service to start it
          MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);

          // Start services loop
          foreach (ServiceBase service in servicesToRun)
          {
              Console.Write("Starting {0} ... ", service.ServiceName);
              onStartMethod.Invoke(service, new object[] { new string[] { } });
              Console.WriteLine("Started");
          }

          // Waiting the end
          Console.WriteLine();
          Console.WriteLine("Press a key to stop services et finish process...");
          Console.ReadKey();
          Console.WriteLine();

          // Get the method to invoke on each service to stop it
          MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);

          // Stop loop
          foreach (ServiceBase service in servicesToRun)
          {
              Console.Write("Stopping {0} ... ", service.ServiceName);
              onStopMethod.Invoke(service, null);
              Console.WriteLine("Stopped");
          }

          Console.WriteLine();
          Console.WriteLine("All services are stopped.");

          // Waiting a key press to not return to VS directly
          if (System.Diagnostics.Debugger.IsAttached)
          {
              Console.WriteLine();
              Console.Write("=== Press a key to quit ===");
              Console.ReadKey();
          }
      }
      static bool HasCommand(String[] args, String command)
      {
          if (args == null || args.Length == 0 || String.IsNullOrWhiteSpace(command)) return false;
          return args.Any(a => String.Equals(a, command, StringComparison.OrdinalIgnoreCase));


      }



Library.cs

public static void WriteErrorLog(Exception ex)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ":" + ex.Source.ToString().Trim() + ";" + ex.Message.ToString().Trim());
                sw.Flush();
                sw.Close();

            }
            catch
            {

            }
        }

        public static void WriteErrorLog(string Message)
        {
            StreamWriter sw = null;
            try
            { 
            
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ":" + Message);
                sw.Flush();
                sw.Close();
            }
            catch
            {

            }


What I have tried:

<pre>i got sample codes on code project simple c#ftp class but i was not able to implement using that. 
Posted
Updated 24-Mar-17 15:21pm
v2
Comments
F-ES Sitecore 23-Mar-17 6:08am    
What's your question?
r.abhaysinghania 23-Mar-17 6:11am    
I need to use ftp instead of that bacth file to transfer the data. and i found the first code on code project but was not able to use it in my code.

1 solution

am I dense (rhetorical) or do I not get what you want to do ..

you don't want to do this

var result = RunProcess(@"D:\Webdata", "cmd.exe", "D:\\Webdata\\Copy_All.bat", false);


but you have code for a ftp class, yes ... so, surely

var result = RunProcess(@"D:\Webdata", "cmd.exe", "D:\\Webdata\\Copy_All.bat", false);
# Instantiate ftp class with parameters
ftp myFTP = new ftp(host, user, password);
# Download the file
myFTP.download(source, localfile);


[edit] obviously this answer is missing a try/catch around the ftp, and possible a 'using', but that's the idea[/edit]

you say somewhere in the comments 'not able to use in my code' ... why not ? what happens when you try ?? don't forget, we cant see your screen, read your mind, we are guided by what you tell us - if you omit something important, then all we can do is sit back here and scratch our heads

There's also a great ftp client here Free .NET FTP library[^] that's worth a look, cheers to the guys at EnterpriseDT, their class saved my bacon before
 
Share this answer
 
v2
Comments
r.abhaysinghania 25-Mar-17 2:33am    
Actually i was not able to understand how to transfer the above( Which runs on batch file) to the code which runs on ftp directly.Thats y i was said I was not able to.

And thank you for the help, I will try the above code.
r.abhaysinghania 25-Mar-17 6:22am    
ERROR: //Unable to cast object of type 'System.Net.FileWebRequest' to type 'System.Net.FtpWebRequest'.
class ftp
{
private string host = null;
private string user = null;
private string pass = null;
private FtpWebRequest ftpRequest = null;
private FtpWebResponse ftpResponse = null;
private Stream ftpStream = null;
private int bufferSize = 2048;

/* Construct Object */
public ftp(string hostIP, string userName, string password) { host = hostIP; user = userName; pass = password; }

/* Download File */
public void download(string remoteFile, string localFile)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);// error here
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Get the FTP Server's Response Stream */
ftpStream = ftpResponse.GetResponseStream();
/* Open a File Stream to Write the Downloaded File */
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
/* Download the File by Writing the Buffered Data Until the Transfer is Complete */
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;
}
}

// Instantiate ftp class with parameters
ftp myFTP = new ftp("//192.168.1.10", "(username)", "(password)");
// Download the file
myFTP.download("//192.168.10.100", "/temp/stock/stock12800");
Garth J Lancaster 25-Mar-17 23:21pm    
well, you havnt supplied the reference on CP for where you obtained the ftp class you're using - nor said how you're using the code - did you include it in a separate file, make sure that had the relevant references & usings etc ? at least the link I gave you has tutorials in the download package
r.abhaysinghania 27-Mar-17 2:07am    
I saw the link you gave but I m not authorize for the same.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900