2016-12-01 98 views
0

我測試了代碼,目錄得到正確的輸入,但由於某種原因它找不到它。有什麼我想念我爲什麼找不到任何目錄?閱讀正確的目錄

這是我現在的代碼非常簡單。

public partial class Form1 : Form 
{ 
    string fileName; 
    string dirName;  

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     dirName = textBox1.Text; 
     fileName = textBox2.Text; 

     if (System.IO.Directory.Exists(dirName)) 
     {    
      if (System.IO.File.Exists(fileName)) 
      {      
       System.IO.File.Delete(fileName); 
      } 
      else 
      { 
       MessageBox.Show("Invalid Directory or File Name"); 
      } 
     } 
    } 
+2

你認爲什麼是「正確的輸入」? – itsme86

+0

你沒有組合目錄名和文件名,值是什麼?我會使用類似Path.Combine(dirName,fileName) –

+0

'dirName'的值是什麼?那麼'fileName'呢? –

回答

0

那是因爲我想你是通過輸入控制傳遞的目錄路徑這樣的「C:/ examplePath /」,它應該以這種方式宣告「C:\\ examplePath」因爲逃逸字符,並且可能會進一步發生錯誤,因爲當您要求存在文件時,必須聲明它將目錄路徑加上文件名(及其擴展名)連接起來。

所以最終的字符串應該是這樣的 「C:\\ \\ exampleDir examplefile.ext」

或者乾脆你應該試試:

dirName = string.Format("@{0}", textBox1.Text); 
fullPathFile = string.Format("{0}/{1}", dirName, textBox2.Text); 

然後使用 「fullPathFile」 代替「fileName」變量。

不要忘記調試你的應用程序,以確保字符串值是什麼。

+1

這wouldnt適用於從UI輸入的文本,它只適用於在設計時編碼的文本。此外,正斜槓(/)是好的,不需要逃脫。此外,你手動組合路徑,使用Path靜態助手簡化你的代碼沒有結束!:) –

0

根據您的代碼,它顯示fileName和dirName來自兩個不同的文本框控件。而且你也不會做任何合併文件路徑的方式(或者看起來如此)。所以,當你打電話給Directory.Exists()這是有道理的,這將工作,但它無法找到該文件。當你使用File.Exists()時,你不僅需要傳入文件名,還需要傳入它所在的目錄。爲此,請使用Path.Combine()方法。

if (System.IO.Directory.Exists(dirName)) 
{ 
    string filePath = System.IO.Path.Combine(dirName, fileName); 

    if (System.IO.File.Exists(filePath)) 
    { 
     System.IO.File.Delete(filePath); 
    } 

    else 
    { 
     MessageBox.Show("Invalid Directory or File Name"); 
    } 
} 
+0

好的,這是更有意義。 –