C#實現bat文件調用


分成2個步驟,首先生成一個bat文件,然后調用批處理文件

1.生成.bat文件

入參為文件的內容,filePath為絕對路徑,且需要擴展名(這個方法不局限於生成.bat文件,也可以生成其他擴展名文件)

 public void writeBATFile(string fileContent)
        {string filePath = "D:\\test\\testChange.bat";
            if (!File.Exists(filePath))
            {
                FileStream fs1 = new FileStream(filePath, FileMode.Create, FileAccess.Write);//創建寫入文件
                StreamWriter sw = new StreamWriter(fs1);
                sw.WriteLine(fileContent);//開始寫入值
                sw.Close();
                fs1.Close();
            }
            else
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Write);
                StreamWriter sr = new StreamWriter(fs);
                sr.WriteLine(fileContent);//開始寫入值
                sr.Close();
                fs.Close();
            }
        }

2.調用.bat文件

這里需要使用一個命名空間

using System.Diagnostics;

調用文件代碼為

  Process proc = null;
            try
            {
                string targetDir = string.Format(@"D:\BizMap\");//this is where testChange.bat lies
                proc = new Process();
                proc.StartInfo.WorkingDirectory = targetDir;
                proc.StartInfo.FileName = "testChange.bat";
                proc.StartInfo.Arguments = string.Format("10");//this is argument
                //proc.StartInfo.CreateNoWindow = true;
                //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//這里設置DOS窗口不顯示,經實踐可行
                proc.Start();
                proc.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM