2013-02-04 42 views
1

我是新來的編碼 - 所以忍受着我。我做了很多閱讀,無法弄清楚這一點。File.Exists - 不想創建新文件

因此,當您運行我的新應用程序時,請鍵入文件夾名稱。該應用轉到該文件夾​​,然後將掃描該指定文件夾中的2個不同的日誌文件。但這裏是我遇到麻煩的地方。如果日誌不存在 - 它會問你是否想創建它正在尋找的文件...我不希望它這樣做。我只是喜歡它去到文件夾,如果該文件不存在,那麼什麼也不做,並轉移到下一行代碼。

這裏是我到目前爲止的代碼:

private void btnGo_Click(object sender, EventArgs e) 
{ 
    //get node id from user and build path to logs 
    string nodeID = txtNodeID.Text; 
    string serverPath = @"\\Jhexas02.phiext.com\rwdata\node\"; 
    string fullPath = serverPath + nodeID; 
    string dbtoolPath = fullPath + "\\DBTool_2013.log"; 
    string msgErrorPath = fullPath + "\\MsgError.log"; 

    //check if logs exist 
    if (File.Exists(dbtoolPath) == true) 
    { 
     System.Diagnostics.Process.Start("notepad.exe", dbtoolPath); 
    } 
    { 
     MessageBox.Show("The 2013 DBTool log does not exist for this Node."); 
    } 

該應用程序將顯示The 2013 DBTool log does not exist for this Node. - 然後打開記事本,並問我是否要創建該文件。

Cannot find the \\Jhexas02.phiext.com\rwdata\node\R2379495\DBTool_2013.log file. 

Do you want to create a new file? 

我不想創建一個新文件。有什麼好方法來解決這個問題?

+1

基於您的代碼,它不會出現記事本應啓動,如果文件不存在後跳過「否則」 ,看起來你沒有給我們完整的代碼。你的應用中是否有其他啓動命令? –

+0

如果文件存在,應該通知用戶dbtool日誌不存在?爲什麼這麼黑幕? –

回答

0

當你的代碼編譯(它是有效的,只是添加護腕那樣)可能是因爲添加elseif語句簡單:

if (File.Exists(dbtoolPath) == true) // This line could be changed to: if (File.Exists(dbtoolPath)) 
{ 
    System.Diagnostics.Process.Start("notepad.exe", dbtoolPath); 
} 
else // Add this line. 
{ 
    MessageBox.Show("The 2013 DBTool log does not exist for this Node."); 
} 

當你的代碼現在看起來,這部分將始終運行:

{ 
    MessageBox.Show("The 2013 DBTool log does not exist for this Node."); 
} 

它本質上是相同的,因爲這代碼:

if (File.Exists(dbtoolPath) == true) 
{ 
    System.Diagnostics.Process.Start("notepad.exe", dbtoolPath); 
} 

MessageBox.Show("The 2013 DBTool log does not exist for this Node."); 
+0

明白了 - 在ELSE語句中添加了工作。感謝大家! – a8e

+0

@ a8e Great =)請記住接受你認爲正確的答案,這樣可以幫助未來的訪問者解決同樣的問題。 –

0

試試這個:

if (File.Exists(dbtoolPath)) 
    { 
     System.Diagnostics.Process.Start("notepad.exe", dbtoolPath); 
    } 
else { 
     MessageBox.Show("The 2013 DBTool log does not exist for this Node."); 
    } 
3

你「如果」

if (File.Exists(dbtoolPath) == true) 
      { 
       System.Diagnostics.Process.Start("notepad.exe", dbtoolPath); 
      } 
      else 
      { 
       MessageBox.Show("The 2013 DBTool log does not exist for this Node."); 
      }