2010-06-09 32 views
1

我正在使用c#.net窗體窗體應用程序。 我必須在defaultsetting.xml文件中保存很少的輸入,但是如果有與具有相同文件名「defaultsetting.xml」的無效文件,我應該在狀態欄中顯示消息。我該怎麼做?如果文件名已存在則顯示一條消息

回答

0

您可以使用File.Exists(路徑)檢查文件是否存在,然後顯示您的消息。

0

您的意思是StatusStrip?

只需向您的StatusStrip添加ToolStripStatusLabel並設置標籤的Text屬性即可。

要檢查文件是否存在,請使用System.IO.File.Exists(filepath)。

0
if (System.IO.File.Exists(@"C:\defaultsettings.xml")) 
    { 
     statusbar1.Text = "Default Settings already exists"; 
    } 

另外,您可以使用此:

 StreamWriter sw = null; 
     try 
     { 
      sw = new StreamWriter((Stream)File.Open(@"C:\DefaultSettings.txt", FileMode.CreateNew)); 
      sw.WriteLine("Test"); 

     } 
     catch (IOException ex) 
     { 
      if (ex.Message.Contains("already exists")) 
      { 
       statusbar1.Text = "File already exists"; 
      } 
      else 
      { 
       MessageBox.Show(ex.ToString()); 
      } 
     } 
     finally 
     { 
      if (sw != null) 
      { sw.Close(); } 
     } 
2

不要使用File.Exists

千萬不要使用File.Exists,它總是引入競爭條件。

取而代之的是,使用「僅限創建」選項以寫模式打開文件,如果文件已存在(以及其他錯誤,例如沒有在該目錄中寫入的權限,網絡共享斷開連接等等)等等)

+1

請描述更多它引入了一個競爭條件? – abatishchev 2010-06-09 12:38:50

+0

http://en.wikipedia.org/wiki/Race_condition – Jimmy 2010-06-09 13:18:54

+1

http://blogs.msdn.com/b/jaredpar/archive/2009/12/10/the-file-system-is-unpredictable.aspx http: //blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx http:// stackoverflow。com/questions/265953 /如何容易檢查,如果訪問被拒絕的文件在網/ 265958#265958 – 2010-06-10 01:04:58

4

問問自己:用戶需要知道該文件無法保存?

如果,那麼通過覆蓋文件來處理它們的情況。由於較少的用戶界面摩擦/垃圾郵件,它將創造更好的體驗。

例A

if (File.Exists(path)) 
     File.Delete(path); 

    Save("defaultsettings.xml"); 

如果,然後檢查文件是否存在,並通過任意顯示MessageBox或您的應用程序StatusStrip改變文本標籤通知用戶。

實例B

if (File.Exists(path)) 
     this.m_StatusBarLabel.Text = "Error: Could not write to file: \"" + path + "\""; 
    else 
     Save("defaultsettings.xml"); 

m_StatusBarLabelToolStripStatusLabel您添加到您的狀態條控件。使用Visual Studio中的設計器一起創建它(這很簡單)。

提示:如果用戶需要執行某些操作,請將文本設置爲HyperLink或添加Click事件。

HTH,

+0

已經調用File.ExistedInTheRecentPast來停止它。 http://blogs.msdn.com/b/jaredpar/archive/2009/12/10/the-file-system-is-unpredictable.aspx – 2010-06-10 01:09:08

+0

@ BenVoight。感謝您的鏈接本。我同意你的看法,即文件系統應該被視爲一個動態共享資源,因爲你不是唯一一個訪問它的人。在瞭解這一點的同時,這個問題和我的答案的重點是如何/何時通知用戶*情況。 – Dennis 2010-06-10 01:54:11

相關問題