2016-01-07 29 views
0

我正在開發一個命令行工具並將路徑作爲參數傳遞給批處理文件。我是否需要將@符號添加到我的應用程序中的內的以防止像「\」這樣的字符被轉義?我應該在命令行中使用@還是符號來提供路徑

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); 
      } 
     } 
+2

轉義發生在字符串文字上。這段代碼中沒有文字,只是變量。沒有必要跳過變量 – Steve

+0

@AH!的內容,所以除非我用路徑聲明變量,否則我不必擔心,是正確的嗎? –

+1

如果使用表示路徑的字符串文字聲明變量AND INITIALIZE IT,則需要文字前面的Verbatim @字符以避免轉義。在您的代碼中,文字來自命令行環境,可能有自己的方式來處理\(如果需要任何方法) – Steve

回答

2

轉義的特殊字符(如「或者)只需要裏面的字符串文字在你的代碼內

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

調用應用程序時無需轉義字符。

但是,例如在使用批處理時,可能會有不同類型的特殊字符以及不同類型的轉義字符。例如,如果您想傳遞「%」(來自批處理),則需要傳遞轉義序列「%%」。

相關問題