Загрузка данных с ftp с помощью службы windows вместо пакетного файла.
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; }
Мой выигрышный сервис
Файл 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"); }
Программа. 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)); }
Библиотека. 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 { }
Что я уже пробовал:
<pre>i got sample codes on code project simple c#ftp class but i was not able to implement using that.
F-ES Sitecore
- Какой у тебя вопрос?
r.abhaysinghania
Мне нужно использовать ftp вместо этого файла bacth для передачи данных. и я нашел первый код в проекте code, но не смог использовать его в своем коде.