gpt4 book ai didi

C# 无法访问该文件,因为它已被其他进程使用

转载 作者:太空宇宙 更新时间:2023-11-03 13:56:15 26 4
gpt4 key购买 nike

我有将 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 block 中它不识别 sw

有什么想法吗?

PS:这行代码抛出一个异常,提示该文件正在被其他进程使用

 using (var sw = new StreamWriter(strFilePath, false))

没有关闭是因为 StreamWriter 没有正确关闭还是因为发送电子邮件正在使用这个文件?

最佳答案

假设您多次输入此代码。
无论哪种情况,您都需要调用 MailMessage 类的 MailMsg.Dispose()。否则,它会保留附件,导致文件在您下次尝试写入时被锁定。

尝试在 MailMessage 上也使用 using 语句

        try 
{
Pers_Conf oConf = LeConf.Get_Config(CodeClient);

using(MailMessage omail = new MailMessage())
{
.....
oSmtp.Send(omail);
}
}
catch (Exception excThrown)
{
throw excThrown;
}

关于C# 无法访问该文件,因为它已被其他进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12087492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com