簡體   English   中英

該進程無法訪問文件“文件名”,因為它正在被另一個進程使用。 並且拒絕訪問路徑“文件名”

[英]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; 為此,我使用唯一的名稱保存文件,然后閱讀最終刪除的文件。

我有時在讀取或刪除文件時遇到錯誤。

在閱讀時我遇到此錯誤

該進程無法訪問文件“文件名”,因為它正在被另一個進程使用。 在System.IO.FileStream.Init(字符串路徑,FileMode模式,FileAccess訪問,Int32權限,布爾useRights,FileShare共享,Int32 bufferSize,FileOptions選項,SECURITY_ATTRIBUTES secAttrs)處的System.IO .__ Error.WinIOError(Int32 errorCode,String mayFullPath) ,位於System.IO.FileStream..ctor的String msgPath,布爾bFromProxy,布爾useLongPath,布爾checkHost)(字符串路徑,FileMode模式,FileAccess訪問,FileShare共享)

刪除時出現此錯誤

拒絕訪問路徑“文件名”。 在System.IO.File.InternalDelete(String path,Boolean checkHost)的System.IO .__ Error.WinIOError(Int32 errorCode,字符串mayFullPath)

我的代碼是:

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
}

我不明白為什么它隨機引發異常。

與其將附件保存到臨時文件中,不如使用不相關的閱讀器打開此文件,然后檢查閱讀器的基本流的長度,然后再使用Outlook.Attachment.Size再次刪除該文件,即可。

您可以用以下方法替換整個方法:

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

另外,簽名bool checksize實際上沒有任何意義,也沒有將文件大小存儲在類成員中,也沒有將其存儲為字符串,但這不是您的問題。

通過在保存和讀取之間添加等待,解決了我的問題。

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM