为什么“1.bat”无法成功运行?任何帮助将不胜感激。 “1.bat”创建成功,可以正常运行,但无法重命名文件。
private void button1_Click(object sender, EventArgs e)
{
string str = System.Environment.CurrentDirectory;
str += "\\1.bat";
string txt = "";
txt = "ren *.mp3 *.wav";
StreamWriter sw = new StreamWriter(str,false, Encoding.UTF8);
sw.Write(txt);
sw.Close();
Process p = new Process();
p.StartInfo.FileName = str;
p.StartInfo.Arguments = "";
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.Start();
}
最佳答案
一个问题是您的文件是使用 UTF-8 BOM 写入的。尝试传递 Encoding.Default
来测试这一点。或者传递 new UTF8Encoding(false)
作为编码来传递省略 BOM 的 UTF-8 编码。
另一个问题(您刚刚在编辑中添加)是您将 UseShellExecute
设置为 false
。这要求您传递的文件是可执行文件。你的文件不是。您需要将 UseShellExecute
设置为 true
才能允许 shell 确定如何处理您的 .bat
文件。
另一个可能的问题是当前目录可能不是您想象的那样。
面对这样的问题,完全没有必要束手无策。进行一些调试。在批处理文件末尾添加 pause
并确保您可以看到控制台。您会立即发现问题所在。学习如何调试与学习如何编程同样重要。在你能做到前者之前,你将无法做到后者。
如果我必须通过外部流程这样做,我会:
- 将
UseShellExecute
设置为false
。 - 将
cmd.exe
作为可执行文件传递。 - 将要执行的命令作为命令行传递。
但是,直接使用 C# 来完成此操作会容易得多,因此可以避免启动外部进程。
关于c# - 如何写入 "*.bat"文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27333097/