[英]ZipFile.CreateFromDirectory throws System.IO.IOException : The process cannot access the file X because it is being used by another process
[英]System.IO.File.Delete throws "The process cannot access the file because it is being used by another process"
每次我使用下面的 function 保存文件並立即刪除它時,我都會收到此錯誤消息:“System.IO.IOException:該進程無法訪問該文件,因為它正在被另一個進程使用”。
等待幾分鍾或關閉 Visual Studio 似乎只能解鎖您之前上傳的文件。
public static bool DeleteFiles(List<String> paths)
{ // Returns true on success
try
{
foreach (var path in paths)
{
if (File.Exists(HostingEnvironment.MapPath("~") + path))
File.Delete(HostingEnvironment.MapPath("~") + path);
}
}
catch (Exception ex)
{
return false;
}
return true;
}
我認為我保存文件的方式可能會導致它們被鎖定。 這是保存文件的代碼:
if (FileUploadCtrl.HasFile)
{
filePath = Server.MapPath("~") + "/Files/" + FileUploadCtrl.FileName;
FileUploadCtrl.SaveAs(filePath)
}
在尋找答案時,我看到有人說您需要關閉 streamReader 但據我了解 SaveAs 方法會自動關閉並處理,所以我真的不知道是什么原因造成的
經過一番測試,我發現了問題所在。 結果我忘記了我每次保存媒體文件時都會調用的 function。 function 返回文件的持續時間並使用 NAudio.Wave.WaveFileReader 和 NAudio.Wave.Mp3FileReader 方法,我在調用它們后忘記關閉它們
我通過將這些方法放在 using 語句中來解決這些問題
這是工作 function:
public static int GetMediaFileDuration(string filePath)
{
filePath = HostingEnvironment.MapPath("~") + filePath;
if (Path.GetExtension(filePath) == ".wav")
using (WaveFileReader reader = new WaveFileReader(filePath))
return Convert.ToInt32(reader.TotalTime.TotalSeconds);
else if(Path.GetExtension(filePath) == ".mp3")
using (Mp3FileReader reader = new Mp3FileReader(filePath))
return Convert.ToInt32(reader.TotalTime.TotalSeconds);
return 0;
}
這個故事的寓意是,檢查您是否在項目的其他任何地方打開文件
我認為問題不在於這里的 streamReader。
運行程序時,程序會在特定文件夾中運行。 基本上,該文件夾已被您的程序鎖定。 在這種情況下,當您關閉程序時,它將被解鎖。
要解決此問題,我建議將寫入/刪除/更新到不同的文件夾。
另一種解決方案可能是檢查文件 readOnly 屬性並更改此處解釋的此屬性
最后一個解決方案可能是使用不同的用戶。 我的意思是,如果您使用不同的用戶而不是管理員創建文件,您可以使用管理員用戶刪除。 但是,我絕對不會使用此解決方案 go 因為如果您不是高級 windows 用戶,管理不同的用戶太棘手了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.