[英]How to delete Zip file after copying into another folder
復制到另一個文件夾后如何刪除zip文件...刪除時出現異常。這是說“文件正在被另一個進程使用”。
string pathString1 = FullFilePath;
string sourceFileName = Path.GetFileName(pathString1);
string foldername = Path.GetDirectoryName(pathString1);
string pathString = Path.Combine(foldername, "Uploaded");
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
string destFile = System.IO.Path.Combine(pathString, sourceFileName);
File.Copy(pathString1, destFile);
File.Delete(pathString1);
File.Delete(FileName);
}
如果解壓縮zip文件,請在using塊或.Dispose()對象中執行此操作,該對象負責解壓縮。 您正在使用什么庫?
為了防止文件被鎖定,在執行完操作后, using語句將釋放該文件:
using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
...
}
再說一次,如果要在復制后立即刪除文件,那為什么不直接移動它呢?
File.Move(from, to);
由於有一種理論認為病毒檢查程序會進入您的.zip文件,因此您可以重試等待重試完成
string pathString1 = FullFilePath;
string sourceFileName = Path.GetFileName(pathString1);
string foldername = Path.GetDirectoryName(pathString1);
string pathString = Path.Combine(foldername, "Uploaded");
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
string destFile = System.IO.Path.Combine(pathString, sourceFileName);
File.Copy(pathString1, destFile);
int itries = 0;
int maxtries = 30; //suitable time of retrying
while (itries++ < maxtries)
{
try
{
File.Delete(pathString1);
itries = 999999;
}
catch (Exception ex)
{
if (itries > maxtries) throw ex;
Thread.Sleep(1000);
}
}
//File.Delete(FileName);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.