2016-07-28 95 views
1

如何复制到另一个文件夹后删除一个zip文件...我在删除时得到异常。它说“该文件正在被另一个进程使用”。如何删除复制到另一个文件夹后的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); 
} 
+1

提供您所使用的工作代码与文件。 –

+0

显示你试图获得帮助的代码。 –

+0

您需要关闭正在使用的流来读取文件。一旦我们看到您的代码,我们可以提供帮助。 –

回答

2

如果解压缩zip文件,则在使用块或.Dispose()负责解压缩的对象中执行此操作。你在用什么库?

2

为了防止文件的锁定,在using语句将释放文件时,它与操作来完成:

using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
{ 
    ... 
} 

话又说回来,如果你删除的文件复制它,那么为什么之后不只是移动它?

File.Move(from, to); 
+0

尝试但同样的例外..无法访问,因为该文件正在被另一个进程使用.. – Pinky

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); 
} 
相关问题