问题描述
我遇到的问题与此处概述的问题几乎相同(),但是该答案与我的情况无关。
我收到了我的简单程序的参数是路径和路径+文件名,其中可能包含很多空格。发生的情况是路径中的空格比我实际产生的参数更多。我通过传递args数组来手动重建所需的内容,但是今天我发现,如果文件名有两个空格,则我的方法将不起作用,并且在程序中无法解决该问题。
I have an issue that's nearly identical to the one outlined here (Console app not parsing correctly args with white spaces) but that answer has no bearing on my situation.
I'm receiving arguments to my simple program that are paths and path+filenames with potentially lots of spaces in them. What's happening is that spaces in the paths are generating many more arguments than I actually have. I was manually reconstructing what I needed by passing through the args array, but I discovered today that if the filename has two spaces my method won't work, and I can't know that in the program to fix it.
So in the case of that set of arguments I get an args[] with 21 elements. Given that there's a pair of spaces at one point I have no hope of correcting this.
Is there anything I can do to make sure that the paths come through in tact? On the giving or receiving end is fine, as I'm in control of both, but not the paths/filenames themselves.
Code:
static void Main(string[] args)
{
//args 0 = Switch value
//args 1 = Working Directory
//args 2 = Mail.dat zip file
if (args.Length == 0)
{
Environment.Exit(-1);
}
string maildatName = args[1].Substring(args[1].IndexOf("Working")+8, args[1].Length - (args[1].IndexOf("Working")+8)) + " ";
for (int x = 2; x < args.Length; x++)
{
maildatName += args[x];
maildatName += " ";
}
args[1] = args[1].Substring(0, args[1].IndexOf("Working") + 7);
maildatName = maildatName.Trim();
}
It is caused by the \"
at the end of your first argument.
If you remove the trailing slash or add an extra slash before the quote then you will get two arguments. The quote is being escaped and is considered part of the first argument until it hits the next quote 2 characters later. After that you are no longer inside of a quote and thus each space results in another argument added to the args
array.
This is caused by the fact that .Net uses CommandLineToArgvW
to process command line arguments and the rules it uses to handle escaping of characters.
Jon Galloway has a writeup on this
To quote:
这篇关于命令行参数,带空格的路径,解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!