该进程无法访问文件 'filename',因为它正被另一个进程使用。并且访问路径 'filename' 被拒绝

the process cannot access the file 'filename' because it is being used by another process. and Access to the path 'filename' is denied

我正在尝试查找文件的大小并将大小存储在 string fileSize = string.Empty; 中。 为此,我用唯一的名称保存文件,然后阅读最后删除文件。

我有时在读取或删除文件时遇到错误。

阅读时出现此错误

the process cannot access the file 'filename' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)

删除时出现此错误

Access to the path 'filename' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.InternalDelete(String path, Boolean checkHost)

我的代码是:

bool checksize(Outlook.Attachment attachment)
{
string currentTime = DateTime.Now.ToString("HHmmssff");
if (!Directory.Exists(GetConfigSettings("folderPath")))
{
Directory.CreateDirectory(GetConfigSettings("folderPath"));
}
attachment.SaveAsFile(GetConfigSettings("folderPath") + "\"+ currentTime + "_" + attachment.FileName);


using (BinaryReader br = new BinaryReader(File.Open(GetConfigSettings("folderPath") + "\"+ currentTime + "_" + attachment.FileName), FileMode.Open)))
{
fileSize = br.BaseStream.Length.ToString();
}

File.Delete(GetConfigSettings("folderPath") + "\"+ currentTime + "_" + attachment.FileName));
//somecode
}

我不明白为什么会随机抛出异常。

不是将附件保存到临时文件,而是使用不相关的 reader 打开此文件,然后检查 reader 的基本流的长度,然后再次删除文件,使用Outlook.Attachment.Size.

您可以将整个方法替换为:

bool checksize(Outlook.Attachment attachment)
{
    filesize = attachment.Size.ToString();
    return true;
}

此外,签名 bool checksize 没有任何意义,将文件大小存储在 class 成员中也没有意义,也没有将其存储为字符串,但这不是你的问题关于。

通过在保存和读取之间添加等待解决了我的问题。

attachment.SaveAsFile(GetConfigSettings("folderPath") + "\"+ currentTime + "_" + attachment.FileName);
System.Threading.Thread.Sleep(100);
using (BinaryReader br = new BinaryReader(File.Open(GetConfigSettings("folderPath") + "\"+ currentTime + "_" + attachment.FileName), FileMode.Open)))
{
fileSize = br.BaseStream.Length.ToString();
}