我必须重命名服务器上的多个文件。为此,我在 Visual Studio 中创建了 ac# 项目。(侧面信息:这个项目也必须做其他事情)现在我尝试从那个项目调用一个批处理文件。此批处理文件必须使用旧文件名和新文件名重命名文件。
这是批处理文件中的代码:
@echo off
set FILENAME_OLD="%~1"
set FILENAME_NEW="%~nx2"
ren %FILENAME_OLD% %FILENAME_NEW%
set error=%errorlevel%
echo %error%
这是我的 c# 项目中的代码:
process.StartInfo.FileName = location;
process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\"", oldfilename, newfilename);
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
result = process.StandardOutput.ReadLine();
结果我总是得到 1。这意味着“ren”不起作用。我在这里做错了什么?
在我的 c# 项目中,文件名都在这样的结构中:@"C:\test\test\test.bat"
编辑:
我有点接近解决方案。问题是我不能将双引号作为参数传递。我需要那些双引号,因为我的一些文件名包含空格。如何将这些文件名正确传递给该批处理文件?
我设法用我认为“肮脏”的方式解决了这个问题:
//I changed newfilename so it's only the filename with extention and not the full path anymore.
string text = "\"" + oldfilename+ "\"" + " " + "\"" + newfilename;
System.IO.File.WriteAllText(@"c:\test\test.txt", text);
process.StartInfo.FileName = location;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
result = process.StandardOutput.ReadLine();
如您所见,我将参数写入了 txt 文件,以便对引号进行转义。
批处理文件现在就像这样简单:
set /p arguments=<c:\test\test.txt
ren %arguments%
echo %errorlevel%
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句