我有一个小实用程序可以使用.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
答案 0 :(得分:2)
可能这是一个简单的错误 传递给CreateFromDirectory的第一个参数应该是目录名,但是您传递文件名。
尝试
If IO.File.Exists(filename) Then
IO.Compression.ZipFile.CreateFromDirectory(Path.GetDirectoryName(filename), _
zippedFile, CompressionLevel.Fastest, True)
End If
答案 1 :(得分: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
需要为ZipArchive
和 System.IO.Compression.FileSystem.dll 添加对{strong> System.IO.Compression.dll 的引用1}}类。在VS中创建项目时,默认情况下不会引用这些DLL。