//生成bat文件,dr包含ftp信息,strBatPath是生成bat文件的路径
private void CreateBAT(DataRow dr, string strBatPath
{
string[] strs;
if(strBatPath.Length != 0)
{
strs = strBatPath.Split('/');
}
else
{
return;
}
if (System.IO.File.Exists(strBatPath))
System.IO.File.Delete(strBatPath);
StringBuilder sBuilder = new StringBuilder();
sBuilder.AppendLine("@echo off");
sBuilder.AppendLine(string.Format("echo open {0}>info.txt", dr["FTPAddress"])); //FTP服务器地址和端口
strIpAddress = dr["FTPAddress"].ToString();
sBuilder.AppendLine(string.Format("echo {0}>>info.txt", dr["FTPUser"]));
sBuilder.AppendLine(string.Format("echo {0}>>info.txt", dr["FTPPwd"]));
sBuilder.AppendLine(string.Format("echo lcd {0}>>info.txt", dr["FTPLocalDirtectory"]));
sBuilder.AppendLine("echo mget *.* >>info.txt");
sBuilder.AppendLine("echo bye>>info.txt");
sBuilder.AppendLine("ftp -i -s:info.txt");
sBuilder.AppendLine("del info.txt");
sBuilder.AppendLine("del %0");
//sBuilder.AppendLine(string.Format("del {0}", strs[strs.Length - 1]));
Stream st = new FileStream(strBatPath, FileMode.OpenOrCreate);
using (StreamWriter sw = new StreamWriter(st))
{
sw.Write(sBuilder.ToString());
sw.Close();
st.Dispose();
st.Close();
}
}
上函数是生成bat文件。里面的内容就是dos命令做的ftp动作。下面函数是执行这个bat文件。
private string ExecuteBAT(string strBatPath,Process pro)//文件路径;要执行bat文件的进程,返回执行结果
{
string mess = "";
try
{
pro.StartInfo.UseShellExecute = true;
pro.StartInfo.FileName = strBatPath; //strBatPath是bat文件路径
pro.StartInfo.CreateNoWindow = true;
if (pro.Start())
{
mess = DateTime.Now.ToLongDateString() + " " + strIpAddress + " 下载备份成功.";//写日志
}
else
{
mess = string.Format("执行{0}失败.", strBatPath);
}
}
catch (Exception ex)
{
mess = ex.Message;
}
finally
{
pro.Close();
}
return mess;
}
这样就实现了执行bat文件。bat文件可以是任何的dos命令组合。