C#执行bat文件

来源:互联网 发布:手机淘宝评论怎么晒图 编辑:程序博客网 时间:2024/05/29 06:49

由于工作需要,要做ftp下载,但是用C#类库,是不是有问题出现。所以决定用批处理做ftp下载。思路是把ftp的信息保存在xml文件中。创建 windows服务,定时的去执行服务。服务的功能是根据xml信息生成bat文件。然后去执行bat文件。

)//生成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命令组合。现在还有问题,就是不能执行多个bat文件。希望有知道原因的告知。

原创粉丝点击