前记:由于项目需要使用silverlight调用webservice发送邮件
在webservice里我用的是自带的System.Net.Mail问题:发送邮件正常,但是邮件发送后文件不释放
可能出现问题代码:
  
//_files是二进制文件流
//filename是路径文件
//创建文件
FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read | FileShare.Write);
stream.SetLength(_files.LongLength);
stream.Write(_files, 0, _files.Length);
stream.Flush();
stream.Close();
stream.Dispose();
GC.Collect(); 
//将二进制转成文件后,文件无法被重新调用或是删除?
//提示:“文件正在被另一个人或程序使用”     
如何在二进制转成文件后,彻底释放这个文件,求助,谢谢!

解决方案 »

  1.   

    System.Runtime.InteropServices.Marshal.ReleaseComObject(AAA)   //AAA為要注釋的對象名
                GC.Collect()
                GC.WaitForPendingFinalizers()
    不知正不正確,敬請樓主嘗試.
      

  2.   

    我刚才判断错误,问题出现在这段代码上:MailMessage _mailMessage = new MailMessage(strFrom, toAddress);
    _mailMessage.Subject = subject; //主题
    _mailMessage.Body = body; //内容
    _mailMessage.BodyEncoding = System.Text.Encoding.UTF8; //正文编码
    _mailMessage.IsBodyHtml = false; //设置为HTML格式
    _mailMessage.Priority = MailPriority.High; //优先级//添加附件
    Attachment Attachment_my = new Attachment(filename);
    _mailMessage.Attachments.Add(Attachment_my);//发送邮件
    _smtpClient.Send(_mailMessage);
    _mailMessage.Attachments.Clear();
    _mailMessage.Attachments.Dispose();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    //文件没有被彻底释放
      

  3.   


    找到问题的根源了
    我循环添加附件
    然后释放Attachment_my,发现释放的是最后一个
    在循环里不能循环释放,那样就会发送失败。
    个人考虑应该用 Attachment[] Attachment_my =null;
    定义成数组形式的。有没有弄过的,告诉我一下,谢谢!foreach (string name in strFiles)

    Attachment_my = new Attachment(filename);
    _mailMessage.Attachments.Add(Attachment_my);
    }
    //发送邮件
    _smtpClient.Send(_mailMessage);
    _mailMessage.Attachments.Clear();
    _mailMessage.Attachments.Dispose();
    Attachment_my.Dispose();
                 
    GC.Collect();
    GC.WaitForPendingFinalizers();
      

  4.   

    问题解决了,谢谢大家!foreach (Attachment attachment in Attachments)
                    {
                        attachment.Dispose();
                    }弄成数组形式循环释放就可以了!
      

  5.   

    楼主。我在邮件发送这一块遇到了问题。
    http://topic.csdn.net/u/20080826/15/b99d3b29-74e5-4684-b33d-0200ab127bac.html
      

  6.   

    其实用using括起来就可以了,自动帮你释放 using(FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read | FileShare.Write))
    {
    stream.SetLength(_files.LongLength);
    stream.Write(_files, 0, _files.Length);
    stream.Flush();
    stream.Close();
    //stream.Dispose();
    //GC.Collect(); 
    }