我有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,但是在其中创建的文件在所有版本的办公室中都不起作用,所以放弃了它。
答案 0 :(得分:2)
试试这个:
protected virtual bool IsLocked(FileInfo fileName)
{
FileStream fStream = null;
try
{
fStream = fileName.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (fStream != null)
{
fStream.Close();
}
}
return false;
}
然后:
if (File.Exists(filePath))
{
FileInfo myfile = new FileInfo(filePath);
if(IsLocked(myfile))
{
File.Create(filePath).Close();
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
else
{
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
}
答案 1 :(得分:1)
我认为问题可能是sendmail在使用完文件之前返回。
我使用了这个释放文件进行删除的函数而不是sendmail():
public static void send(string subject, string body, string from, string to, List<string> attachments = null)
{
using (MailMessage message = new MailMessage(new MailAddress(from), new MailAddress(to)))
{
message.Subject = subject;
message.Body = body;
if (attachments != null && attachments.Count > 0)
{
foreach (string s in attachments)
{
if (s != null)
{
/* this code fixes the error where the attached file is
* prepended with the path of the file */
Attachment attachment = new Attachment(s, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(s);
disposition.ModificationDate = File.GetLastWriteTime(s);
disposition.ReadDate = File.GetLastAccessTime(s);
disposition.FileName = Path.GetFileName(s);
disposition.Size = new FileInfo(s).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
}
}
using (SmtpClient client = new SmtpClient())
{
client.Send(message);
}
}
}