文件无法重写,因为其他进程使用该文件

File can´t rewritten because other process uses the file

我用 C# 编写了一些代码来将文件作为 .eml 文件的附件发送。
我在 Windows 临时文件夹中创建文件并将它们附加到 .eml 文件。 .eml 文件只需打开并通过 Process.Start(filename); 使用 windows 中的标准邮件程序发送。如果用户希望再次发送该文件,该文件将从数据库中重写以确保其为最新版本。

现在我的问题是:随机几次或仅在第一次之后重写文件时出现错误

The process cannot access the file because it is being used by another process

我实际上在网上做了一些研究并发现了另一个 question
所以我确保像那里提到的那样,FileStream 已正确设置所有参数。
var fs = new FileStream(tempPathSave, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)
有人知道我的问题是什么原因吗?我最大的问题是,当我这样做或那样做时,我无法真正复制它来说明它正在发生。

编辑: 我在 using 语句中使用 FileStream 以确保它被正确处理。

如果不实际查看代码,很难正确理解问题所在,但根据我的经验,您没有正确处理文件流对象,因此它保留了文件句柄

var fs = new FileStream(tempPathSave, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)

因此,当您使用完文件流后,调用

fs.Dispose();

这将正确处理您的文件流。

此外,您可以使用语法糖,using 它将自动处理您的对象

using(var fs = new FileStream(tempPathSave, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)){
// use fs here
// STUFF
} //at the end fs will be disposed

我找到了解决问题的办法。我刚刚将 FileStream 更改为 MemoryStream,因为 MailMessage 构造函数也可以处理流。唯一的一点是,在保存 .eml 文件之前,您必须保持 MemoryStream 打开。更重要的是,您必须注意内存使用情况,并确保之后处理每个 MemoryStream。