我是否应该使用@或//符号从命令行

时间:2016-01-07 18:15:37

标签: c# command-line path

我正在开发一个命令行实用程序,并将路径作为参数传递到批处理文件中。我是否需要将@符号添加到我的应用程序中的路径中,以防止“\”之类的字符转义?

这个link指定使用@符号,但是目前,我没有使用@或\\来防止转义。当我按原样进入我的路径时,它工作正常。这是为什么?

我会在我的批处理文件中这样称呼它:

foldercleaner.exe -tPath: "C:\Users\Someuser\DirectoryToClean"

程序:

class Program
    {
        public static void Main(string[] args)
        {
            if(args[0] == "-tpath:" || args[0] == "-tPath:"  && !isBlank(args[1]))  {
                    clearPath(args[1]);
            }
            else{

                Console.WriteLine("Parameter is either -tpath:/-tPath: and you must provide a valid path");
            }
    }  

清除路径方法:

public static void clearPath(string path)
        {
            if(Directory.Exists(path)){

                int directoryCount = Directory.GetDirectories(path).Length;

                if(directoryCount > 0){

                    DirectoryInfo di = new DirectoryInfo(path);

                    foreach (DirectoryInfo dir in di.GetDirectories())
                    {
                        dir.Delete(true); 
                    }

                }
                else{

                    Console.WriteLine("No Subdirectories to Remove");
                }

                int fileCount = Directory.GetFiles(path).Length;

                if(fileCount > 0){

                    System.IO.DirectoryInfo di = new DirectoryInfo(path);

                    foreach (FileInfo file in di.GetFiles())
                    {
                            file.Delete(); 
                    }


                }
                else{

                    Console.WriteLine("No Files to Remove");
                }

                }
            else{

                Console.WriteLine("Path Doesn't Exist {0}", path);
            }
        }

1 个答案:

答案 0 :(得分:2)

转义特殊字符(例如“或”)只需在代码中的字符串文字内

var str = "This is a literal";
var str2 = otherVariable; //This is not a literal

调用应用程序时无需转义字符。

但是,例如,在使用Batch时,可能会有一组不同的特殊字符,这些特殊字符具有不同类型的转义字符。例如,如果要传递“%”(来自Batch),则需要传递转义序列“%%”。