2

我有一个可以使用 .net 4.5 TripleDES 例程加密/解密的小实用程序。我添加了压缩,发现更简单的压缩东西对我不起作用。

这些字段中引用的文件肯定存在,根本不是很大,甚至在相同的情况下命名。

但是我不断收到“目录名称无效。”。如果我对存档的存在进行测试,我会得到一个不同的错误 - 因为它是 zip 并且它是 0 字节。与昨天弄清楚如何使用我的实用程序的加密部分相比,我已经搜索了更长的时间 - 那就是学习流的工作原理!

任何人都可以阐明这个问题吗?

Private Encoded As String = "C:\TestFile\encoded.txt"
Private Decoded As String = "C:\TestFile\decoded.txt"
Private CompressEncoded As String = "C:\TestFile\encoded.zip"

Private Sub Main()
  Compress(Encoded, CompressEncoded)
End sub

Sub Compress(filename As String, zippedFile As String)
'Added to handle file already exists error
  If IO.File.Exists(zippedFile) Then IO.File.Delete(zippedFile)
  If IO.File.Exists(filename) Then IO.Compression.ZipFile.CreateFromDirectory(filename, zippedFile, CompressionLevel.Fastest, True)
End Sub

除了这段代码之外,我还尝试添加一个快速流读取器测试来向自己证明文件名确实存在。' Dim sr As New StreamReader(filename) MessageBox.Show(sr.ReadToEnd)

它执行并显示其中的文本行。

我将不胜感激 - 这个相当愚蠢的错误今天下午已经占用了很多时间,我希望将其用于更有用的东西:)。

谢谢各位!

感谢你的回答!

Sub Compress(filename As String, zippedFile As String)
    If IO.File.Exists(zippedFile) Then IO.File.Delete(zippedFile)

    If IO.File.Exists(filename) Then
        Using archive As ZipArchive = Open(zippedFile, ZipArchiveMode.Create)
            archive.CreateEntryFromFile(filename, Path.GetFileName(filename), CompressionLevel.Fastest)
        End Using

    End If
End Sub

Sub Decompress(ZippedFile As String, UnzippedFile As String)
    If IO.File.Exists(UnzippedFile) Then IO.File.Delete(UnzippedFile)

    If IO.File.Exists(ZippedFile) Then
        Using archive As ZipArchive = Open(ZippedFile, ZipArchiveMode.Read)
            archive.ExtractToDirectory(Path.GetDirectoryName(UnzippedFile))
        End Using
    End If
End Sub
4

2 回答 2

3

可能这是一个简单的错误。
传递给CreateFromDirectory的第一个参数应该是目录名,但您传递的是文件名。

尝试

 If IO.File.Exists(filename) Then 
      IO.Compression.ZipFile.CreateFromDirectory(Path.GetDirectoryName(filename), _
                        zippedFile, CompressionLevel.Fastest, True)
 End If
于 2013-06-16T17:03:53.940 回答
2

如果要压缩单个文件,请使用ZipArchive如下类:

Sub Compress(filename As String, zippedFile As String)
    If IO.File.Exists(zippedFile) Then IO.File.Delete(zippedFile)

    If IO.File.Exists(filename) Then
        Using archive As ZipArchive = ZipFile.Open(zippedFile, ZipArchiveMode.Create)
            archive.CreateEntryFromFile(filename, Path.GetFileName(filename), CompressionLevel.Fastest)
        End Using

    End If
End Sub

附加信息

需要为类添加对System.IO.Compression.dllZipArchiveSystem.IO.Compression.FileSystem.dll引用ZipFile。在 VS 中创建项目时,默认情况下不会引用这些 DLL。

于 2013-06-16T17:31:13.107 回答