我有转移SQL为CSV代码:我通过电子邮件发送的CSV文件C#不能访问该文件,因为它被其他进程
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();
}
之后:
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("[email protected]", "xxxxxx"),
EnableSsl = true
};
omail.From = new MailAddress("[email protected]");
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
无法正常关闭,或者是因为发送电子邮件使用此文件关闭正在使用?
你能不能上线,你得到的异常更具体?在最初使用? – Steve
这种情况发生在程序第一次访问这个函数,或者整个过程(build,send)重复使用同一个文件名不止一次? – Steve
它发生在第二次程序访问此功能 – user609511