使用Windows服务而不是批处理文件从ftp下载数据。 [英] Downloading data from ftp using windows service instead of batch file.
问题描述
首先抱歉我无法更新问题,因为我无法访问网络连接。@ Richard和@Sunasara
我需要从以下网址下载数据一个特定的服务器使用Windows服务对我下面的目录说例如//192.16.124.30,这样无论何时服务运行,它都会删除旧数据并自行下载新数据。我有一个服务,通过批处理文件执行此操作,但它花了很多时间,所以我试图通过ftp做到这一点!
c:\ webdata \ jhstock
C:\ webdata \ mistar
下面是我的win服务代码和示例代码在代码项目中找到简单的c #FTP类
这是我在代码项目的网站上找到的代码
< pre>类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 =密码; }
/ *下载文件* /
public void download(string remoteFile,string localFile)
{
try
{
/ *创建FTP请求* /
ftpRequest =(FtpWebRequest)FtpWebRequest.Create(host +/+ remoteFile);
/ *使用用户名和密码登录FTP服务器* /
ftpRequest.Credentials = new NetworkCredential(user,pass);
/ *如有疑问,请使用以下选项* /
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/ *指定FTP请求的类型* /
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
/ *建立与FTP服务器的返回通信* /
ftpResponse =(FtpWebResponse)ftpRequest.GetResponse();
/ *获取FTP服务器的响应流* /
ftpStream = ftpResponse.GetResponseStream();
/ *打开文件流写下载文件* /
FileStream localFileStream = new FileStream(localFile,FileMode.Create);
/ *下载数据的缓冲区* /
byte [] byteBuffer = new byte [bufferSize];
int bytesRead = ftpStream.Read(byteBuffer,0,bufferSize);
/ *通过写入缓冲数据下载文件直到转移完成* /
尝试
{
while(bytesRead> 0)
{
localFileStream.Write(byteBuffer,0,bytesRead);
bytesRead = ftpStream.Read(byteBuffer,0,bufferSize);
}
}
catch(Exception ex){Console.WriteLine(ex.ToString()); }
/ *资源清理* /
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch(Exception ex){Console.WriteLine(ex.ToString()); }
返回;
}
我的获胜服务
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秒
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)
{
//成功
Console.WriteLine(成功);
}
其他
{
//错误ErrorLevel / app ExitCode
Console.WriteLine(再次尝试失败);
}
}
protected override void OnStop()
{
timer1.Enabled = false ;
Library.WriteErrorLog(测试服务已结束);
}
Program.cs
static void Main(String [] args)
{
//初始化服务以启动
ServiceBase [] ServicesToRun;
ServicesToRun = new ServiceBase []
{
new Service1()
};
//在交互模式下?
if(Environment.UserInteractive)
{
//在调试模式下?
if(System.Diagnostics.Debugger.IsAttached)
{
//模拟服务执行
RunInteractiveServices(ServicesToRun);
}
其他
{
尝试
{
bool hasCommands = false;
//有安装命令吗?
if(HasCommand(args,install))
{
ManagedInstallerClass.InstallHelper(new String [] {typeof(Program).Assembly.Location});
hasCommands = true;
//有一个启动命令?
if(HasCommand(args,start))
{
foreach(ServicesToRun中的var服务)
{
ServiceController sc = new ServiceController(service.ServiceName) ;
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running,TimeSpan.FromSeconds(10));
}
hasCommands = true;
}
}
//有停止命令?
if(HasCommand(args,stop))
{
foreach(ServicesToRun中的var服务)
{
ServiceController sc = new ServiceController(service.ServiceName) ;
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped,TimeSpan.FromSeconds(10000)); //更改
}
hasCommands = false;
}
//有卸载命令吗?
if(HasCommand(args,uninstall))
{
ManagedInstallerClass.InstallHelper(new String [] {/ u,typeof(Program).Assembly.Location});
hasCommands = true;
}
//如果我们没有命令,我们打印使用消息
if(!hasCommands)
{
Console。 WriteLine(用法:{0} [命令] [命令...],Environment.GetCommandLineArgs());
Console.WriteLine(Commands:);
Console.WriteLine( - install:安装服务);
Console.WriteLine( - uninstall:卸载服务);
}
}
catch(exception ex)
{
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(错误:{0},ex.GetBaseException()。Message);
Console.ForegroundColor = oldColor;
}
}
}
else
{
//正常服务执行
ServiceBase.Run(ServicesToRun);
}
}
static void RunInteractiveServices(ServiceBase [] servicesToRun)
{
Console.WriteLine();
Console.WriteLine(以交互模式启动服务。);
Console.WriteLine();
//获取调用每个服务的方法以启动它
MethodInfo onStartMethod = typeof(ServiceBase).GetMethod(OnStart,BindingFlags.Instance | BindingFlags.NonPublic);
//启动服务循环
foreach(servicesToRun中的ServiceBase服务)
{
Console.Write(Starting {0} ...,service.ServiceName );
onStartMethod.Invoke(service,new object [] {new string [] {}});
Console.WriteLine(已开始);
}
//等待结束
Console.WriteLine();
Console.WriteLine(按一个键停止服务和完成进程...);
Console.ReadKey();
Console.WriteLine();
//获取调用每个服务的方法来停止它
MethodInfo onStopMethod = typeof(ServiceBase).GetMethod(OnStop,BindingFlags.Instance | BindingFlags.NonPublic);
//停止循环
foreach(servicesToRun中的ServiceBase服务)
{
Console.Write(Stopping {0} ...,service.ServiceName) ;
onStopMethod.Invoke(service,null);
Console.WriteLine(已停止);
}
Console.WriteLine();
Console.WriteLine(所有服务都已停止。);
//等待按键不直接返回VS
if(System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine();
Console.Write(===按键退出===);
Console.ReadKey();
}
}
static bool HasCommand(String [] args,String command)
{
if(args == null || args.Length == 0 | | String.IsNullOrWhiteSpace(command))返回false;
return args.Any(a => String.Equals(a,command,StringComparison.OrdinalIgnoreCase));
}
Library.cs
public static void WriteErrorLog(exception ex)
{
StreamWriter sw =空值;
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();
}
捕获
{
}
我尝试了什么:
< pre>我在代码项目简单的c#ftp类上得到了示例代码,但我是无法实现使用它。
我是密集的(修辞)还是我没有得到你想要的东西..
你不想这样做
var result = RunProcess(@D:\ Webdata ,cmd.exe,D:\\Webdata \\Copy_All.bat,false);
但你有ftp类的代码,是的......所以,当然
var result = RunProcess(@D :\ Webdata,cmd.exe,D:\\Webdata \\Copy_All.bat,false);
#使用参数
实例化ftp类ftp myFTP = new ftp(主机,用户,密码);
#下载文件
myFTP.download(source,localfile);
显然这个答案错过了ftp周围的try / catch,可能是'使用',但这就是想法[/ edit]
你在评论的某处说'不能在我的代码中使用'...为什么不呢?当你尝试时会发生什么?别忘了,我们无法看到你的屏幕,读到你的想法,我们受到你告诉我们的指导 - 如果你省略了一些重要的东西,那么我们所能做的就是坐在这里划伤我们的脑袋
这里还有一个很棒的ftp客户端免费的.NET FTP库 [ ^ ]值得一看,为EnterpriseDT的人欢呼,他们的班级在我之前保存了我的培根
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.
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
这篇关于使用Windows服务而不是批处理文件从ftp下载数据。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!