如何在复制到另一个文件夹后删除一个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);
}
答案 0 :(得分:2)
如果解压缩zip文件,则在using块或.Dispose()中执行此操作,负责解压缩。您使用的是什么库?
答案 1 :(得分:2)
为防止锁定文件,using语句将在完成操作后释放文件:
using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
...
}
然后,如果您在复制后立即删除文件,那么为什么不移动它?
File.Move(from, to);
答案 2 :(得分:0)
因为有一种理论认为病毒检查程序会进入你的.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);
}