出现 7-Zip 错误 - 无法将带空格的文件名传递给 Process.Start() 方法
Getting 7-Zip error - Unable to pass File-names with spaces to Process.Start() method
我需要将 .zip 文件位置传递到下面 c# 代码中的 files
参数。
如果文件名不包含空格,则一切正常。但是,如果文件名包含空格,则会抛出以下错误。
Cannot find archive
下面是我的代码:有人可以建议我如何解决这个问题吗?
static void UnzipToFolder(string zipPath, string extractPath, string[] files)
{
string zipLocation = ConfigurationManager.AppSettings["zipLocation"];
foreach (string file in files)
{
string sourceFileName = string.Empty;
string destinationPath = string.Empty;
var name = Path.GetFileNameWithoutExtension(file);
sourceFileName = Path.Combine(zipPath, file);
destinationPath = Path.Combine(extractPath, name);
var processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = zipLocation;
processStartInfo.Arguments = @"x " + sourceFileName + " -o" + destinationPath;
processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
var process = Process.Start(processStartInfo);
process.WaitForExit();
}
}
在文件路径周围添加引号:
processStartInfo.Arguments = "x \"" + sourceFileName + "\" -o \"" + destinationPath + "\"";
或为了可读性(使用 C# 6):
processStartInfo.Arguments = $"x \"{sourceFileName}\" -o \"{destinationPath}\"";
所有包含空格的文件名和路径都必须用引号引起来。
接下来,关于你的问题,把路径写成这样怎么样:
7z a -tzip C:\abc\zipfilename C:\"Program files"\DirectoryOrFile
我需要将 .zip 文件位置传递到下面 c# 代码中的 files
参数。
如果文件名不包含空格,则一切正常。但是,如果文件名包含空格,则会抛出以下错误。
Cannot find archive
下面是我的代码:有人可以建议我如何解决这个问题吗?
static void UnzipToFolder(string zipPath, string extractPath, string[] files)
{
string zipLocation = ConfigurationManager.AppSettings["zipLocation"];
foreach (string file in files)
{
string sourceFileName = string.Empty;
string destinationPath = string.Empty;
var name = Path.GetFileNameWithoutExtension(file);
sourceFileName = Path.Combine(zipPath, file);
destinationPath = Path.Combine(extractPath, name);
var processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = zipLocation;
processStartInfo.Arguments = @"x " + sourceFileName + " -o" + destinationPath;
processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
var process = Process.Start(processStartInfo);
process.WaitForExit();
}
}
在文件路径周围添加引号:
processStartInfo.Arguments = "x \"" + sourceFileName + "\" -o \"" + destinationPath + "\"";
或为了可读性(使用 C# 6):
processStartInfo.Arguments = $"x \"{sourceFileName}\" -o \"{destinationPath}\"";
所有包含空格的文件名和路径都必须用引号引起来。
接下来,关于你的问题,把路径写成这样怎么样:
7z a -tzip C:\abc\zipfilename C:\"Program files"\DirectoryOrFile