C# 执行 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命令组合。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值