使用Using无法读取流

我遇到错误

  

文件正在被另一个进程使用

尝试为using实现FileStream。但是,我遇到了Stream was not readable错误。

这是我的代码:

之前:可以正常工作,但是会定期遇到“文件正在被另一个进程使用”错误

EmailMessage responseMessageWithAttachment = responseMessage.Save();

foreach (var attachment in email.Attachments)
{
    if (attachment is FileAttachment)
    {
        FileAttachment fileAttachment = attachment as FileAttachment;
        fileAttachment.Load();
        fileAttachment.Load(AppConfig.EmailSaveFilePath + fileAttachment.Name);

        FileStream fs = new FileStream(AppConfig.EmailSaveFilePath + fileAttachment.Name,FileMode.OpenOrCreate);
        responseMessageWithAttachment.Attachments.AddFileAttachment(attachment.Name,fs);
    }
}
responseMessageWithAttachment.SendAndSaveCopy();

之后:遇到“流不可读”错误

EmailMessage responseMessageWithAttachment = responseMessage.Save();

foreach (var attachment in email.Attachments)
{
    if (attachment is FileAttachment)
    {
        FileAttachment fileAttachment = attachment as FileAttachment;
        fileAttachment.Load();
        fileAttachment.Load(AppConfig.EmailSaveFilePath + fileAttachment.Name);

        using (FileStream fs = new FileStream(AppConfig.EmailSaveFilePath + fileAttachment.Name,FileMode.OpenOrCreate))
        {
            responseMessageWithAttachment.Attachments.AddFileAttachment(attachment.Name,fs);
        };
    }
}
responseMessageWithAttachment.SendAndSaveCopy();
ckwcaowei 回答:使用Using无法读取流

  

工作正常,但会定期遇到“文件正在被另一个进程使用”错误

这意味着它的意思:其他某个进程正在触摸该文件。如果要解决此问题,则需要弄清楚正在使用什么文件。无论您是否使用using,都会发生这种情况。

如果此代码并行运行多次,则可能是您自己的代码干扰。无论哪种方式,您都可以通过仅打开以只读的方式来避免它,但是特别允许其他进程打开以进行写入。您将这样做:

var fs = new FileStream(Path.Combine(AppConfig.EmailSaveFilePath,fileAttachment.Name),FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
  

遇到“流不可读”错误

这取决于如何实现AddFileAttachment。您不会显示堆栈跟踪,因此有可能直到您调用SendAndSaveCopy()之外的using并且流被关闭之后,它才会读取流。

解决此问题的一种简单方法是仅使用the overload of AddFileAttachment that just takes the path to the file as a string,因此您无需自己管理FileStream

responseMessageWithAttachment.Attachments.AddFileAttachment(attachment.Name,Path.Combine(AppConfig.EmailSaveFilePath,fileAttachment.Name));

我使用Path.Combine是因为它可以避免在您的\设置中可能存在尾随的EmailSaveFilePath时出现问题。

,

我想知道是否可以避免保存文件而仅使用ContentAddFileAttachment(String,Byte[])

foreach (var attachment in email.Attachments)
{
    if (attachment is FileAttachment)
    {
        FileAttachment fileAttachment = attachment as FileAttachment;
        fileAttachment.Load();
        responseMessageWithAttachment.Attachments.AddFileAttachment(attachment.Name,fileAttachment.Content);
    }
}
responseMessageWithAttachment.SendAndSaveCopy();
本文链接:https://www.f2er.com/3098140.html

大家都在问