2012-08-17 89 views
-2

我正在以.csv文件生成報告。如果再次打開文件,則會出現錯誤

我使用下面的代碼通過按鈕單擊事件上的代碼打開一個.csv文件。

StreamWriter sw = new StreamWriter(AbsolutePathAndFileName); 

     //write header line 
     int iColCount = TheDataTable.Columns.Count; 
     for (int i = 0; i < iColCount; i++) 
     { 
      sw.Write(TheDataTable.Columns[i]); 
      if (i < iColCount - 1) 
      { 
       sw.Write(separator); 
      } 
     } 
     sw.Write(sw.NewLine); 

     //write rows 
     foreach (DataRow dr in TheDataTable.Rows) 
     { 
      for (int i = 0; i < iColCount; i++) 
      { 
       if (!Convert.IsDBNull(dr[i])) 
       { 
        string data = dr[i].ToString(); 
        data = data.Replace("\"", "\\\"").Replace(",", " "); 
        sw.Write(quote + data + quote); 
       } 
       if (i < iColCount - 1) 
       { 
        sw.Write(separator); 
       } 
      } 
      sw.Write(sw.NewLine); 
     } 
     sw.Close(); 



MsgBox db = new MsgBox("Please select below option.", "Message", MessageBoxIcon.Information); 
       db.SetButtons("Open Master File", "Save Master File", strBasePath + "\\master.csv"); 
       db.ShowDialog(this); 

此代碼適合我。

現在我的文件處於打開模式。如果過濾另一個條件再次打開報告(.csv文件) 比它向我拋出錯誤,該文件被另一個進程使用。

我該如何解決這個錯誤?

+0

你用什麼代碼打開它? – 2012-08-17 06:51:25

+2

爲什麼不能在使用後關閉它? – Jeeva 2012-08-17 06:51:30

+1

「如果」?你爲什麼不知道? – 2012-08-17 06:51:39

回答

0

ChrisW已就Is there a way to check if a file is in use?

一個很好的回答,您可以檢查您的文件是否是在使用或不使用此示例代碼:

protected virtual bool IsFileLocked(FileInfo file) 
{ 
    FileStream stream = null; 

    try 
    { 
     stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
    } 
    catch (IOException) 
    { 
     //the file is unavailable because it is: 
     //still being written to 
     //or being processed by another thread 
     //or does not exist (has already been processed) 
     return true; 
    } 
    finally 
    { 
     if (stream != null) 
      stream.Close(); 
    } 

    //file is not locked 
    return false; 
} 

希望這幫助。

+0

此代碼不適用於我。我得到了一個例外 stream = file.Open(FileMode.Open,FileAccess.ReadWrite,FileShare.None); finally finally condition is not satisfied .. as stream returns null to me – 2012-08-17 06:59:42

+0

你應該更新你的問題 - 這是一個非常重要的細節!什麼是類型,拋出異常的消息? – 2012-08-17 07:03:41

+0

@RogerTaylor我已更新我的帖子,請檢查 – 2012-08-17 07:25:06

相關問題