【问题标题】:How to delete Zip file after copying into another folder复制到另一个文件夹后如何删除Zip文件
【发布时间】:2016-07-28 19:15:05
【问题描述】:

复制到另一个文件夹后如何删除 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);
}

【问题讨论】:

  • 提供您用于处理文件的代码。
  • 显示您尝试获取帮助的代码。
  • 您需要关闭用于读取文件的流。一旦我们看到您的代码,我们就可以提供帮助。
  • 我已经编辑了我的问题
  • 代码中的大括号在哪里?只有一个孤独的人

标签: c# .net


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    为防止文件被锁定,using 语句将在操作完成后释放文件:

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

    再一次,如果您在复制文件后立即删除它,那为什么不直接移动它呢?

    File.Move(from, to);
    

    【讨论】:

    • 试过了,但也有同样的异常..无法访问,因为该文件正在被另一个进程使用..
    【解决方案3】:

    由于有病毒检查程序进入您的 .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);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      • 2013-02-08
      • 2019-02-08
      相关资源
      最近更新 更多