我有将 SQL 转换为 CSV 的代码:
public void CreateCSVFile(DataTable dt, string strFilePath, bool Is_Ordre, int TypeDonne)
{
//FileStream fs = new FileStream(strFilePath, FileMode.Create);
// FileStream fs = File.Create(strFilePath);
// Create the CSV file to which grid data will be exported.
//StreamWriter sw = new StreamWriter(fs);
//StreamWriter sw = new StreamWriter(strFilePath, false);
using (var sw = new StreamWriter(strFilePath, false))
{
// First we will write the headers.
//DataTable dt = m_dsProducts.Tables[0];
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
if (Is_Ordre) sw.Write(", TYP_DONNE");
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write("\'" + dr[i].ToString().Replace("'", " ").Replace(",", ".") + "\'");
}
else
{
sw.Write("\' \'");
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
if (Is_Ordre) sw.Write(", \'" + TypeDonne + "\'");
sw.Write(sw.NewLine);
}
sw.Flush();
sw.Close();
sw.Dispose();
}
//fs.Close();
}
之后,我通过电子邮件发送 CSV 文件:
Attachment data_OD = new Attachment(LeSource, MediaTypeNames.Application.Octet);
Attachment data_LV = new Attachment(LeSource_LV, MediaTypeNames.Application.Octet);
oEmail.SendingEmail(ClientID, data_OD, data_LV);
public void SendingEmail(string CodeClient, Attachment dataOD, Attachment dataLV)
{
try
{
Pers_Conf oConf = LeConf.Get_Config(CodeClient);
MailMessage omail = new MailMessage();
var oSmtp = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("xxxxxx@gmail.com", "xxxxxx"),
EnableSsl = true
};
omail.From = new MailAddress("xxxxx@gmail.com");
omail.To.Add(oConf.EmailAddr);
omail.Subject = "xxxxxx_" + CodeClient;
omail.Body = CodeClient;
omail.Attachments.Add(dataOD);
omail.Attachments.Add(dataLV);
oSmtp.Send(omail);
}
catch (Exception excThrown)
{
throw excThrown;
}
似乎StreamWriter
没有正确关闭文件,我已经尝试过:
Try
{
StreamWriter sw = new StreamWriter(strFilePath, false);
}
Catch
{
}
Finaly
{
sw.Flush();
sw.Close();
sw.Dispose();
}
但在finally
块中它不识别sw
。
任何的想法 ?
PS:这行代码抛出一个异常,告诉其他进程正在使用该文件
using (var sw = new StreamWriter(strFilePath, false))
没有关闭是因为StreamWriter
没有正确关闭还是因为发送电子邮件正在使用这个文件?