我有一個windows服務,它定期從表中提取數據並創建excel文件並將其郵寄給用戶。發送郵件後,我需要刪除該文件。已使用以下代碼:當試圖刪除文件時正在使用'文件正在使用'#
public void LABInstrumentExcelGeneration(string filePath) {
try {
string connectionString = GetConnectionString(filePath);
List <LABInstruments> listLABInstrument = null;
listLABInstrument = new List <LABInstruments>();
listLABInstrument = LABInstrumentBL.GetLABInstrumentList();
if (listLABInstrument.Count > 0) {
using(OleDbConnection conn = new OleDbConnection(connectionString)) {
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "CREATE TABLE [table2] (SrNo string,CalibrationDoneOn Date);";
cmd.ExecuteNonQuery();
foreach(LABInstruments tc1 in listLABInstrument) {
cmd.CommandText = "INSERT INTO [table2](SrNo,CalibrationDoneOn) VALUES('" + tc1.SrNo + "','" + tc1.CalibrationDoneOn + "');";
cmd.ExecuteNonQuery();
}
conn.Close();
conn.Dispose();
}
}
} catch (Exception ex) {}
}
SendMail(filePath, role);
if (File.Exists(filePath)) {
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
但它給出錯誤文件正被另一個進程使用。 何可以刪除文件嗎?而且,我使用OLEDB創建文件。是否有任何其他文件創建的最佳做法?已經嘗試過ExcelLibrary,但在其中創建的文件不適用於所有版本的辦公室,因此放棄了它。
你並不需要使用'conn.Close()'和'conn.Dispose();'因爲該對象將由於使用塊而自動處理。同時使用參數化查詢來避免sql注入 – Izzy
當你的服務創建這些文件時,你在創建之後確保File.Close()嗎? – uk2k05
我沒有明確地打開該文件,因此不需要file.Close()。 – Priya