ZipFileExtensions.CreateEntryFromFile Метод
Определение
Архивирует файл, сжимая его и добавляя его в ZIP-архив.Archives a file by compressing it and adding it to the zip archive.
Перегрузки
CreateEntryFromFile(ZipArchive, String, String) |
Архивирует файл, сжимая его и добавляя его в ZIP-архив.Archives a file by compressing it and adding it to the zip archive. |
CreateEntryFromFile(ZipArchive, String, String, CompressionLevel) |
Архивирует файл, сжимая его с использованием заданного уровня сжатия и добавляя его в ZIP-архив.Archives a file by compressing it using the specified compression level and adding it to the zip archive. |
CreateEntryFromFile(ZipArchive, String, String)
Архивирует файл, сжимая его и добавляя его в ZIP-архив.Archives a file by compressing it and adding it to the zip archive.
public:
[System::Runtime::CompilerServices::Extension]
static System::IO::Compression::ZipArchiveEntry ^ CreateEntryFromFile(System::IO::Compression::ZipArchive ^ destination, System::String ^ sourceFileName, System::String ^ entryName);
public static System.IO.Compression.ZipArchiveEntry CreateEntryFromFile (this System.IO.Compression.ZipArchive destination, string sourceFileName, string entryName);
static member CreateEntryFromFile : System.IO.Compression.ZipArchive * string * string -> System.IO.Compression.ZipArchiveEntry
<Extension()>
Public Function CreateEntryFromFile (destination As ZipArchive, sourceFileName As String, entryName As String) As ZipArchiveEntry
Параметры
- destination
- ZipArchive
ZIP-архив, в который добавляется файл.The zip archive to add the file to.
- sourceFileName
- String
Путь к файлу, который необходимо заархивировать.The path to the file to be archived. Можно указать относительный или абсолютный путь.You can specify either a relative or an absolute path. Относительный путь интерпретируется относительно текущего рабочего каталога.A relative path is interpreted as relative to the current working directory.
- entryName
- String
Имя записи, которую требуется создать в ZIP-архиве.The name of the entry to create in the zip archive.
Возвращаемое значение
Программа-оболочка для новой записи в ZIP-архиве.A wrapper for the new entry in the zip archive.
Исключения
sourceFileName
имеет значение Empty, содержит только пробел или по крайней мере один недопустимый символ.sourceFileName
is Empty, contains only white space, or contains at least one invalid character.
-или--or-
entryName
имеет значение Empty.entryName
is Empty.
Параметр sourceFileName
или entryName
имеет значение null
.sourceFileName
or entryName
is null
.
В sourceFileName
длина указанного пути, имени файла или обоих параметров превышает установленное в системе максимальное значение.In sourceFileName
, the specified path, file name, or both exceed the system-defined maximum length.
Недопустимый sourceFileName
(например, он ведет на несопоставленный диск).sourceFileName
is invalid (for example, it is on an unmapped drive).
Файл, указанный в sourceFileName
, не может быть открыт или слишком большой для изменения (текущий предел: MaxValue).The file specified by sourceFileName
cannot be opened, or is too large to be updated (current limit is MaxValue).
Параметр sourceFileName
задает каталог.sourceFileName
specifies a directory.
-или--or-
У вызывающего объекта отсутствует разрешение на доступ к файлу, указанному параметром sourceFileName
.The caller does not have the required permission to access the file specified by sourceFileName
.
Файл, заданный параметром sourceFileName
, не найден.The file specified by sourceFileName
is not found.
Параметр sourceFileName
имеет недопустимый формат.The sourceFileName
parameter is in an invalid format.
-или--or- ZIP-архив не поддерживает запись.The zip archive does not support writing.
ZIP-архив был удален.The zip archive has been disposed.
Примеры
В следующем примере показано, как создать новую запись в ZIP-архиве из существующего файла.The following example shows how to create a new entry in a zip archive from an existing file.
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string zipPath = @"c:\users\exampleuser\start.zip";
string extractPath = @"c:\users\exampleuser\extract";
string newFile = @"c:\users\exampleuser\NewFile.txt";
using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
{
archive.CreateEntryFromFile(newFile, "NewEntry.txt");
archive.ExtractToDirectory(extractPath);
}
}
}
}
Imports System.IO
Imports System.IO.Compression
Module Module1
Sub Main()
Dim zipPath As String = "c:\users\exampleuser\end.zip"
Dim extractPath As String = "c:\users\exampleuser\extract"
Dim newFile As String = "c:\users\exampleuser\NewFile.txt"
Using archive As ZipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Update)
archive.CreateEntryFromFile(newFile, "NewEntry.txt", CompressionLevel.Fastest)
archive.ExtractToDirectory(extractPath)
End Using
End Sub
End Module
Комментарии
Новая запись в архиве содержит содержимое файла, указанного параметром sourceFileName
.The new entry in the archive contains the contents of the file specified by sourceFileName
. Если запись с указанным именем ( entryName
) уже существует в архиве, то создается вторая запись с идентичным именем.If an entry with the specified name (entryName
) already exists in the archive, a second entry is created with an identical name. LastWriteTimeСвойство записи устанавливается в момент последнего изменения файла в файловой системе.The LastWriteTime property of the entry is set to the last time the file on the file system was changed.
При ZipArchiveMode.Update
наличии ограничения на размер записи ограничивается Int32.MaxValue .When ZipArchiveMode.Update
is present, the size limit of an entry is limited to Int32.MaxValue. Это ограничение связано с тем, что режим обновления использует внутреннее приложение, MemoryStream чтобы разрешить поиск, необходимый при обновлении архива, и MemoryStream он имеет максимальный размер, равный значению типа int.This limit is because update mode uses a MemoryStream internally to allow the seeking required when updating an archive, and MemoryStream has a maximum equal to the size of an int.
Применяется к
CreateEntryFromFile(ZipArchive, String, String, CompressionLevel)
Архивирует файл, сжимая его с использованием заданного уровня сжатия и добавляя его в ZIP-архив.Archives a file by compressing it using the specified compression level and adding it to the zip archive.
public:
[System::Runtime::CompilerServices::Extension]
static System::IO::Compression::ZipArchiveEntry ^ CreateEntryFromFile(System::IO::Compression::ZipArchive ^ destination, System::String ^ sourceFileName, System::String ^ entryName, System::IO::Compression::CompressionLevel compressionLevel);
public static System.IO.Compression.ZipArchiveEntry CreateEntryFromFile (this System.IO.Compression.ZipArchive destination, string sourceFileName, string entryName, System.IO.Compression.CompressionLevel compressionLevel);
static member CreateEntryFromFile : System.IO.Compression.ZipArchive * string * string * System.IO.Compression.CompressionLevel -> System.IO.Compression.ZipArchiveEntry
<Extension()>
Public Function CreateEntryFromFile (destination As ZipArchive, sourceFileName As String, entryName As String, compressionLevel As CompressionLevel) As ZipArchiveEntry
Параметры
- destination
- ZipArchive
ZIP-архив, в который добавляется файл.The zip archive to add the file to.
- sourceFileName
- String
Путь к файлу, который необходимо заархивировать.The path to the file to be archived. Можно указать относительный или абсолютный путь.You can specify either a relative or an absolute path. Относительный путь интерпретируется относительно текущего рабочего каталога.A relative path is interpreted as relative to the current working directory.
- entryName
- String
Имя записи, которую требуется создать в ZIP-архиве.The name of the entry to create in the zip archive.
- compressionLevel
- CompressionLevel
Одно из значений перечисления, указывающее, акцентировать ли внимание на скорости или эффективности сжатия при создании записи.One of the enumeration values that indicates whether to emphasize speed or compression effectiveness when creating the entry.
Возвращаемое значение
Программа-оболочка для новой записи в ZIP-архиве.A wrapper for the new entry in the zip archive.
Исключения
sourceFileName
имеет значение Empty, содержит только пробел или по крайней мере один недопустимый символ.sourceFileName
is Empty, contains only white space, or contains at least one invalid character.
-или--or-
entryName
имеет значение Empty.entryName
is Empty.
Параметр sourceFileName
или entryName
имеет значение null
.sourceFileName
or entryName
is null
.
Недопустимый sourceFileName
(например, он ведет на несопоставленный диск).sourceFileName
is invalid (for example, it is on an unmapped drive).
В sourceFileName
длина указанного пути, имени файла или обоих параметров превышает установленное в системе максимальное значение.In sourceFileName
, the specified path, file name, or both exceed the system-defined maximum length.
Файл, указанный в sourceFileName
, не может быть открыт или слишком большой для изменения (текущий предел: MaxValue).The file specified by sourceFileName
cannot be opened, or is too large to be updated (current limit is MaxValue).
Параметр sourceFileName
задает каталог.sourceFileName
specifies a directory.
-или--or-
У вызывающего объекта отсутствует разрешение на доступ к файлу, указанному параметром sourceFileName
.The caller does not have the required permission to access the file specified by sourceFileName
.
Файл, заданный параметром sourceFileName
, не найден.The file specified by sourceFileName
is not found.
Параметр sourceFileName
имеет недопустимый формат.The sourceFileName
parameter is in an invalid format.
-или--or- ZIP-архив не поддерживает запись.The zip archive does not support writing.
ZIP-архив был удален.The zip archive has been disposed.
Примеры
В следующем примере показано, как создать новую запись в ZIP-архиве на основе существующего файла и указать уровень сжатия.The following example shows how to create a new entry in a zip archive from an existing file, and specify the compression level.
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string zipPath = @"c:\users\exampleuser\start.zip";
string extractPath = @"c:\users\exampleuser\extract";
string newFile = @"c:\users\exampleuser\NewFile.txt";
using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
{
archive.CreateEntryFromFile(newFile, "NewEntry.txt", CompressionLevel.Fastest);
archive.ExtractToDirectory(extractPath);
}
}
}
}
Imports System.IO
Imports System.IO.Compression
Module Module1
Sub Main()
Dim zipPath As String = "c:\users\exampleuser\end.zip"
Dim extractPath As String = "c:\users\exampleuser\extract"
Dim newFile As String = "c:\users\exampleuser\NewFile.txt"
Using archive As ZipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Update)
archive.CreateEntryFromFile(newFile, "NewEntry.txt", CompressionLevel.Fastest)
archive.ExtractToDirectory(extractPath)
End Using
End Sub
End Module
Комментарии
Новая запись в архиве содержит содержимое файла, указанного параметром sourceFileName
.The new entry in the archive contains the contents of the file specified by sourceFileName
. Если запись с указанным именем ( entryName
) уже существует в архиве, то создается вторая запись с идентичным именем.If an entry with the specified name (entryName
) already exists in the archive, a second entry is created with an identical name. LastWriteTimeСвойство записи устанавливается в момент последнего изменения файла в файловой системе.The LastWriteTime property of the entry is set to the last time the file on the file system was changed.
При ZipArchiveMode.Update
наличии ограничения на размер записи ограничивается Int32.MaxValue .When ZipArchiveMode.Update
is present, the size limit of an entry is limited to Int32.MaxValue. Это ограничение связано с тем, что режим обновления использует внутреннее приложение, MemoryStream чтобы разрешить поиск, необходимый при обновлении архива, и MemoryStream он имеет максимальный размер, равный значению типа int.This limit is because update mode uses a MemoryStream internally to allow the seeking required when updating an archive, and MemoryStream has a maximum equal to the size of an int.