0

我使用 libNunrar 站点来提取.rar文件:

RarArchive.WriteToDirectory(fs.Name, Path.Combine(@"D:\DataDownloadCenter", path2), ExtractOptions.Overwrite);

解压工作正常,但我无法在提取操作后删除原始压缩文件

System.IO.File.Delete(path);

因为该文件被另一个进程使用, 所以孔函数:

 try
           {
               FileStream fs = File.OpenRead(path);
               if(path.Contains(".rar")){

                   try
                   {
                       RarArchive.WriteToDirectory(fs.Name, Path.Combine(@"D:\DataDownloadCenter", path2), ExtractOptions.Overwrite);
                       fs.Close();

                   }
                   catch { }

                   }

           catch { return; }
           finally
           {
               if (zf != null)
               {
                   zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                   zf.Close(); // Ensure we release resources
               }
           }
           try
           {
               System.IO.File.Delete(path);
           }
           catch { }

那么我可以在解压后删除压缩文件吗?

4

2 回答 2

1

我不知道是什么zf,但您也可以将其包含在using声明中。尝试用FileStream fs这个替换你的部分

using( FileStream fs = File.OpenRead(path))
{
    if(path.Contains(".rar"))
    {
        try
        {
           RarArchive.WriteToDirectory(fs.Name, Path.Combine(@"D:\DataDownloadCenter", path2), ExtractOptions.Overwrite);
        }
        catch { }
     }
}

fs即使path不包含,这种方式也是关闭的.rar。您只关闭文件名中存在的fsif 。rar

另外,图书馆有自己的流处理吗?它可能有一个关闭它的方法。

于 2013-07-04T10:52:12.993 回答
0

我也有这个问题,nunrar、nether close() 或 using 语句似乎可以解决这个问题。不幸的是,文档很少,所以我现在使用SharpCompress 库,根据 nunrar 的开发人员,它是 nunrar 库的一个分支。关于 SharpCompress 的文档也很少(但更少)所以这是我使用的方法:

private static bool unrar(string filename)
{
    bool error = false;
    string outputpath = Path.GetDirectoryName(filename);

    try
    {
        using (Stream stream = File.OpenRead(filename))
        {
            var reader = ReaderFactory.Open(stream);
            while (reader.MoveToNextEntry())
            {
                if (!reader.Entry.IsDirectory)
                {
                    Console.WriteLine(reader.Entry.Key);
                    reader.WriteEntryToDirectory(outputpath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
                }
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Failed: " + e.Message);
        error = true;
    }

    if (!error)
    {
        File.Delete(filename);
    }
    return error;
}

将以下库添加到顶部

using SharpCompress.Common;
using SharpCompress.Readers;

使用 nuget 安装。此方法适用于 SharpCompress v0.22.0(撰写本文时最新)

于 2018-10-16T19:33:35.310 回答