I am trying to access a file in a .7z file. I know the name of the file in the zip folder and that it exists in the .7z file. Previously I've used the ExtractArchive(templocation) which just dumps all the files into a temporary location. Now I want to be able to grab a specific file without extracting the whole .7z file.
7Zip has a class called the SevenZipExtractor that has a method ExtractFile. I would think that is what I am looking for, but I can't find any decent documentation on it.
What I need clarification on is how to go about getting the Stream parameter passed in correctly.
I am using code like this;
//this grabs the zip file and creates a FileInfo array that hold the .7z file (assume there is only one)
DirectoryInfo directoryInfo = new DirectoryInfo(ApplicationPath);
FileInfo[] zipFile = directoryInfo.GetFiles("*.7z");
//This creates the zipextractor on the zip file I just placed in the zipFile FileInfo array
using (SevenZip.SevenZipExtractor zipExtractor = new SevenZip.SevenZipExtractor(zipFile[0].FullName))
//Here I should be able to use the ExtractFile method, however I don't understand the stream parameter, and I can't find any good documentation on the method itself. What is this method looking for?
{
zipExtractor.ExtractFile("ConfigurationStore.xml", Stream stream);
}
Setup a FileStream that SevenZip can write out to:
DirectoryInfo directoryInfo = new DirectoryInfo(ApplicationPath);
FileInfo[] zipFile = directoryInfo.GetFiles("*.7z");
using (SevenZip.SevenZipExtractor zipExtractor = new SevenZip.SevenZipExtractor(zipFile[0].FullName))
{
using (FileStream fs = new FileStream("", FileMode.Create)) //replace empty string with desired destination
{
zipExtractor.ExtractFile("ConfigurationStore.xml", fs);
}
}
Related
I'm using System.IO.Compression in order to compress a file into a .zip, below the source code:
using (FileStream zipToOpen = new FileStream(zipName, FileMode.CreateNew)){
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)){
ZipArchiveEntry readmeEntry = archive.CreateEntry(#"C:\Users\soc\myFold\someFile.xml");
}
}
This piece of code works well, but unfortunately in the .zip there's the entire sequence of folders (C: -> Users -> ... -> someFile.xml); can I obtain a final .zip with ONLY the file I need? I know that with other libraries this fact is possible (DotNetZip add files without creating folders), but I would like to know if it were possible do the same with the standard library.
You seem to be under the impression that the file will be added to the archive, which is not the case. CreateEntry merely creates an entry with the specified path and entry name, you still need to write the actual file.
In fact, the code in your question is quite similar to the code in the documentation, so I assume you got it from there?
Anyway, to get only the file name you can use Path.GetFileName and then you can write the actual file content to the zip entry.
var filePath = #"C:\temp\foo.txt";
var zipName = #"C:\temp\foo.zip";
using (FileStream zipToOpen = new FileStream(zipName, FileMode.CreateNew))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.CreateEntry(Path.GetFileName(filePath));
using (StreamReader reader = new StreamReader(filePath))
using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
{
writer.Write(reader.ReadToEnd());
}
}
}
The code above will create an archive with foo.txt in the root and with the content of the source file, without any additional directories.
I'm wondering if there is a best practice when it comes to working with .tmp file for writing data. I like to make an .tmp that will be use in the filestream and then when I close the writer, I like to rename the file. Is there a way to rename file extension?
FileStream stream2 = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
StreamWriter streamWriter2 = new StreamWriter(stream2);
streamWriter2.WriteLine(textToAdd);
streamWriter2.Close();
string changed = Path.ChangeExtension(fileName, .txt);
File.Move(path, changed);
Here's how I would do this:
// Build a FileInfo object for your temp destination, this gives us
// access to a handful of useful file manipulation methods
var yourFile = new FileInfo(#"C:\temp\testfile.tmp");
// open a StreamWriter to write text to the file
using (StreamWriter sw = yourFile.CreateText())
{
// Write your text
sw.WriteLine("Test");
// There's no need to call Close() when you're using usings
}
// "Rename" the file -- this is the fastest way in C#
yourFile.MoveTo(#"C:\temp\testfile.txt");
You can use Path.GetFilenameWithoutExtension to remove the extension and then just add the one you want.
Does the .NET ZipArchive allow to rename or move entries? Currently it's not possible to change the name of a ZipArchiveEntry once it is created. It seems that I have to copy the stream of the original ZipArchiveEntry to a newly ZipArchiveEntry with the changed name.
Thanks
Martin
I don't know what "move" would mean, other than to rename an entry. Even in regular disk file systems, a "move" really is just a rename where the full path of the file name has changed, not just the "leaf node" file name. In a .zip archive, this is even more explicit; a "directory" or "folder" in an archive exists only by virtue of an entry having that directory name in its name (separated, of course, by a directory separator character). So "move" is exactly the same as "rename".
As far as whether you can rename things, no…with ZipArchive, you will have to create a new entry that is a copy of the original, but with the new name, and then delete the original.
Code to do that would look like this:
static void RenameEntry(this ZipArchive archive, string oldName, string newName)
{
ZipArchiveEntry oldEntry = archive.GetEntry(oldName),
newEntry = archive.CreateEntry(newName);
using (Stream oldStream = oldEntry.Open())
using (Stream newStream = newEntry.Open())
{
oldStream.CopyTo(newStream);
}
oldEntry.Delete();
}
Implemented as an extension method, as above, you can call like this:
ZipArchive archive = ...; open archive in "update" mode
string oldName = ...,
newName = ...; // names initialized as appropriate
archive.RenameEntry(oldName, newName);
I'm a new .Net developper and i'm facing an issue while developping an Uploaded Zip File in a document Library.
i need to extract the content of the Zip File uploaded to do some actions on the files contained in it.
So i choosed to use ZipArchive Stream to handle my problem, i can retrieve my SPFile from my DocLib easily and create the stream from it.
But i'm not able to create embedded files from ZipArchiveEntry, i tried the following piece of code ( not a copy/past, i'm not on my dev machine )
foreach(SPFile myFile in mySPFolder.Files)
{
ZipArchive myZip = new ZipArchive(myFile.OpenBinaryStream());
foreach(ZipArchiveEntry subZip in ZipArchive.Entries)
{
SPFile newFile = list.RootFolder.Add("myxml.xml",subZip.Open())
}
}
I'm facing an issue while creating my newFile as it's throwing me a System I/O error, as per my understanding it's maybe due to the fact that the stream returned by the method ZipArchiveEntry.Open() is a deflatestream.
I saw that the file creation can be done with a MemoryStream, but i'm not able to understand how to convert a deflatestream to a memorystream.
I got the solution from another place but..
In order to get a memorystream from a deflatestream you need to use the CopyTo() method from Stream.
public void ExtractLibraryZipFolder(SPWeb web, SPList myList, string FolderPath, SPFile myFile, bool overWrite)
{
ZipArchive myZip = new ZipArchive(myFile.OpenBinaryStream());
foreach (ZipArchiveEntry subZip in myZip.Entries)
{
MemoryStream myMemoryStream = new MemoryStream();
subZip.Open().CopyTo(myMemoryStream);
if (FolderPath != string.Empty)
{
SPFolder theFolder = web.GetFolder("/ImportToolLibrary/");
theFolder.SubFolders[FolderPath].Files.Add(subZip.Name, myMemoryStream);
}
else
{
SPFile myUpload = myList.RootFolder.Files.Add(subZip.Name, myMemoryStream);
}
}
}
Given a stream object which contains an xlsx file, I want to save it as a temporary file and delete it when not using the file anymore.
I thought of creating a class that implementing IDisposable and using it with the using code block in order to delete the temp file at the end.
Any idea of how to save the stream to a temp file and delete it on the end of use?
Thanks
You could use the TempFileCollection class:
using (var tempFiles = new TempFileCollection())
{
string file = tempFiles.AddExtension("xlsx");
// do something with the file here
}
What's nice about this is that even if an exception is thrown the temporary file is guaranteed to be removed thanks to the using block. By default this will generate the file into the temporary folder configured on the system but you could also specify a custom folder when invoking the TempFileCollection constructor.
You can get a temporary file name with Path.GetTempFileName(), create a FileStream to write to it and use Stream.CopyTo to copy all data from your input stream into the text file:
var stream = /* your stream */
var fileName = Path.GetTempFileName();
try
{
using (FileStream fs = File.OpenWrite(fileName))
{
stream.CopyTo(fs);
}
// Do whatever you want with the file here
}
finally
{
File.Delete(fileName);
}
Another approach here would be:
string fileName = "file.xslx";
int bufferSize = 4096;
var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose)
// now use that fileStream to save the xslx stream
This way the file will get removed after closing.
Edit:
If you don't need the stream to live too long (eg: only a single write operation or a single loop to write...), you can, as suggested, wrap this stream into a using block. With that you won't have to dispose it manually.
Code would be like:
string fileName = "file.xslx";
int bufferSize = 4096;
using(var fileStream = System.IO.File.Create(fileName, bufferSize, System.IO.FileOptions.DeleteOnClose))
{
// now use that fileStream to save the xslx stream
}
// Get a random temporary file name w/ path:
string tempFile = Path.GetTempFileName();
// Open a FileStream to write to the file:
using (Stream fileStream = File.OpenWrite(tempFile)) { ... }
// Delete the file when you're done:
File.Delete(tempFile);
EDIT:
Sorry, maybe it's just me, but I could have sworn that when you initially posted the question you didn't have all that detail about a class implementing IDisposable, etc... anyways, I'm not really sure what you're asking in your (edited?) question. But this question: Any idea of how to save the stream to temp file and delete it on the end of use? is pretty straight-forward. Any number of google results will come back for ".NET C# Stream to File" or such.
I just suggest for creating file use Path.GetTempFileName(). but others depends on your usage senario, for example if you want to create it in your temp creator class and use it just there, it's good to use using keyword.