I have a .lst file that has the paths of various data that has to be zipped. The path may be a direct path to an executable or a path to a log file or may contain a wildcard like - c:\abc*.exe. How do I zip all of them into a single zip file? Thanks
DotNetZip Library is #:http://dotnetzip.codeplex.com/wikipage?title=CS-examples&referringTitle=Examples
Contents of .lst file :
c:\log\abc.log
c:\log\def.log
c:\ping*.bat
c:\ping*.exe
This is what I tried:
using (ZipFile zip = new ZipFile())
{
StreamReader file = File.OpenText("C:\\pingman\\pingzipA.lst");
string read = String.Empty;
while ((read = file.ReadLine()) != null)
{
zip.AddSelectedFiles(read, true);
zip.Save("c:\\update.zip");
}
file.Close();
}
Try something like:
while ((read = file.ReadLine()) != null)
{
if (read.Contains("*"))
{
zip.AddSelectedFiles(read, true);
}
else
{
zip.AddFile(read);
}
}
zip.Save("c:\\update.zip");
Here is a link that has a TON of Examples take a look as use the examples to work for what you are trying to do.. there is even an example that uses Wild-Cards
DontNetZip Library Site with Examples
Got it to work.
if (read.Contains("*"))
{
int i = read.IndexOf("*");
string path = read.Substring(0, i--);
string doc = read.Substring(i+1);
zip.AddSelectedFiles(doc, #path, true);
}
else
{
zip.AddFile(read);
}
Related
I am trying to read a zip file with I get via IFormFile and I am going through the files inside to unzip a selected extension and unzip it but I cannot use the IFormFile to read it. It says cannot convert IFormFile to string.
Any suggestions on how to tackle this?
using (ZipArchive archive = ZipFile.OpenRead(file))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (entry.FullName.EndsWith(".dbf", StringComparison.OrdinalIgnoreCase))
{
RedirectToAction("Index");
}
}
}
Because IFormFile != string. I guess OpenRead expects a file path.
So, first read the content of the IFormFile into a file, then use that file path.
Although this won't help in this particular case (since ZipFile.OpenRead() expects a file), for those coming here after googling "iformfile to string", you can read an IFormFile into a string, for example as follows:-
var result = new StringBuilder();
using (var reader = new StreamReader(iFormFile.OpenReadStream()))
{
while (reader.Peek() >= 0)
{
result.AppendLine(reader.ReadLine());
}
}
Hi I'm writing a c# code where in there is a string sent as a parameter input to the method. And then the inputString has to be searched in the file and the result has to be returned. Currently I know how do I do this in the regular way(using the file IO).
[HttpPost]
public string UsernameValidation(string username)
{
string text = username;
string userExists = usernameNotAvailable;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("~/UserData/usernameslist.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(text))
{
userExists = usernameAvailable;
}
}
return userExists;
}
But here is the twist, my project is in MVC. I'm able to get the path of file using string userDataFile = Server.MapPath("~/UserData/usernameslist.txt");.
But I'm unable to know how can I get the functionality of searching a string in a file.
Please let me know how can I do this.
Thanks
If the the file usernameslist.txt really exists inside a subfolder named UserData from your root folder then you just need to pass the output of Server.MapPath to your StreamReader constructor
string fileName = Server.MapPath("~/UserData/usernameslist.txt");
using(StreamReader file = new System.IO.StreamReader(fileName))
{
....
}
And don't forget to use the using statement around a Stream object
i'm trying to save multiple images with File.WriteAllBytes(), even after i tried to seperate between the saves with 'Thread.Sleep()' it's not working..
my code:
byte[] signatureBytes = Convert.FromBase64String(model.Signature);
byte[] idBytes = Convert.FromBase64String(model.IdCapture);
//Saving the images as PNG extension.
FileManager.SaveFile(signatureBytes, dirName, directoryPath, signatureFileName);
FileManager.SaveFile(idBytes, dirName, directoryPath, captureFileName);
SaveFile Function:
public static void SaveFile(byte[] imageBytes, string dirName, string path, string fileName, string fileExt = "jpg")
{
if (!string.IsNullOrEmpty(dirName)
&& !string.IsNullOrEmpty(path)
&& !string.IsNullOrEmpty(fileName)
&& imageBytes.Length > 0)
{
var dirPath = Path.Combine(path, dirName);
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
di.Create();
if (di.Exists)
{
File.WriteAllBytes(dirPath + $#"\{fileName}.{fileExt}", imageBytes);
}
}
else
throw new Exception("File cannot be created, one of the parameters are null or empty.");
}
File.WriteAllBytes():
"Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten"
As expecify in :
https://msdn.microsoft.com/en-ca/library/system.io.file.writeallbytes(v=vs.110).aspx
So if you can only see the last one, you are overwriting the file.
Apart from the possibility (as mentioned by #Daniel) that you're overwriting the same file, I'm not sure about this code:
var di = new DirectoryInfo(dirPath);
if (!di.Exists)
di.Create();
if (di.Exists)
{
...
}
I'd be surprised if, having called di.Create(), the Exists property is updated. In fact, it is not updated - I checked.
So, if the directory did not exist, then you won't enter the conditional part even after creating the directory. Could that explain your issue?
While there is a response to this question using the java libraries (Read a zip file inside zip file), I cannot find an example of this anywhere in c# or vb.net.
What I have to do for a client is use the .NET 4.5 ZipArchive library to traverse zip files for specific entries. Before anyone asks, the client refuses to allow me to use dotnetzip, because his chief architect has experience with that library and says it is too buggy to be used in a real application. He's pointed out a couple to me, and it doesn't matter what I think anyway!
If I have a zip file, that itself contains other zip files, I need a way of opening the inner zip files, and read the entries for that zip file. Eventually I will also have to actually open the zip entry for the zip in a zip, but for now I just have to be able to get at the zipentries of an inner zip file.
Here's what I have so far:
public string PassThruZipFilter(string[] sfilters, string sfile, bool buseregexp, bool bignorecase, List<ZipArchiveZipFile> alzips)
{
bool bpassed = true;
bool bfound = false;
bool berror = false;
string spassed = "";
int ifile = 0;
try
{
ZipArchive oarchive = null; ;
int izipfiles = 0;
if (alzips.Count == 0)
{
oarchive = ZipFile.OpenRead(sfile);
izipfiles = oarchive.Entries.Count;
}
else
{
//need to dig into zipfile n times in alzips[i] where n = alzips.Count
oarchive = GetNthZipFileEntries(alzips, sfile); <------ NEED TO CREATE THIS FUNCTION!
izipfiles = oarchive.Entries.Count;
}
while (((ifile < izipfiles) & (bfound == false)))
{
string sfilename = "";
sfilename = oarchive.Entries[ifile].Name;
//need to take into account zip files that contain zip files...
bfound = PassThruFilter(sfilters, sfilename, buseregexp, bignorecase);
if ((bfound == false) && (IsZipFile(sfilename)))
{
//add this to the zip stack
ZipArchiveZipFile ozazp = new ZipArchiveZipFile(alzips.Count, sfile, sfilename);
alzips.Add(ozazp);
spassed = PassThruZipFilter(sfilters, sfilename, buseregexp, bignorecase, alzips);
if (spassed.Equals(sISTRUE))
{
bfound = true;
}
else
{
if (spassed.Equals(sISFALSE))
{
bfound = false;
}
else
{
bfound = false;
berror = true;
}
}
}
ifile += 1;
}
}
catch (Exception oziperror)
{
berror = true;
spassed = oziperror.Message;
}
if ((bfound == false))
{
bpassed = false;
}
else
{
bpassed = true;
}
if (berror == false)
{
spassed = bpassed.ToString();
}
return (spassed);
}
So the function I have to create is 'GetNthZipFileEntries(List, sfile)', where the ZipFileZipEntry is just a structure that contains an int index, string szipfile, string szipentry.
I cannot figure out how read a zip file inside a zip file (or G-d forbid, a zip file inside a zip file inside a zip file...the 'PassThruZipFilter is a function inside a recursive function) using .NET 4.5. Obviously microsoft does it, because you can open up a zip file inside a zip file in explorer. Many thanks for anyone that can help.
So, I truly need your help on how to open zip files inside of zip files in .NET 4.5 without writing to the disk. There are NO examples on the web I can find for this specific purpose. I can find tons of examples for reading zip file entries, but that doesn't help. To be clear, I cannot use a hard disk to write anything. I can use a memory stream, but that is the extent of what I can do. I cannot use the dotnetzip library, so any comments using that won't help, but of course I'm thankful for any help at all. I could use another library like the Sharp zip libs, but I'd have to convince the client that it is impossible with .NET 4.5.
Once you identify a ZipArchiveEntry as a Zipfile, you can call the Open method on the entry to obtain a Stream. That stream can then be used to create a new ZipArchive.
The following code demonstrates listing all entries and sub-entries of a nested Zip archive.
Private Sub Test()
Using strm As Stream = File.Open("Textfile.zip", FileMode.Open)
ListZipEntries(strm)
End Using
End Sub
Private Sub ListZipEntries(strm As Stream)
Using archive As New ZipArchive(strm, ZipArchiveMode.Read, False) ' closes stream when done
For Each entry As ZipArchiveEntry In archive.Entries
Debug.Print(entry.FullName)
Dim fi As New FileInfo(entry.FullName)
If String.Equals(fi.Extension, ".zip", StringComparison.InvariantCultureIgnoreCase) Then
Debug.IndentLevel += 1
Using entryStream As Stream = entry.Open()
ListZipEntries(entryStream)
End Using
Debug.IndentLevel -= 1
End If
Next
End Using
End Sub
I want to zip one "CSV" file in to Zip file using C#.Net. Below i have written some code for create Zip file , using this code i am able to create zip file but after creating "Data1.zip" file extract manually means extracted file extension should be ".csv" but it is not coming.
FileStream sourceFile = File.OpenRead(#"C:\Users\Rav\Desktop\rData1.csv");
FileStream destFile = File.Create(#"C:\Users\Rav\Desktop\Data1.zip");
GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress,false);
try
{
int theByte = sourceFile.ReadByte();
while (theByte != -1)
{
compStream.WriteByte((byte)theByte);
theByte = sourceFile.ReadByte();
}
}
finally
{
compStream.Dispose();
}
http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx
This is gzip compression, and apparently it only compresses a stream, which when decompressed takes the name of the archive without the .gz extension. I don't know if I'm right here though. You might as well experiment with the code from MSDN, see if it works.
I used ZipLib for zip compression. It also supports Bz2, which is a good compression algorithm.
Use ICSharpCode.SharpZipLib(you can download it) and do the following
private void CreateZipFile(string l_sFolderToZip)
{
FastZip z = new FastZip();
z.CreateEmptyDirectories = true;
z.CreateZip(l_sFolderToZip + ".zip", l_sFolderToZip, true, "");
if (Directory.Exists(l_sFolderToZip))
Directory.Delete(l_sFolderToZip, true);
}
private void ExtractFromZip(string l_sFolderToExtract)
{
string l_sZipPath ="ur folder path" + ".zip";
string l_sDestPath = "ur location" + l_sFolderToExtract;
FastZip z = new FastZip();
z.CreateEmptyDirectories = true;
z.ExtractZip(l_sZipPath, l_sDestPath, "");
if (File.Exists(l_sZipPath))
File.Delete(l_sZipPath);
}
Hope it helps...
Use one of these libraries:
http://www.icsharpcode.net/opensource/sharpziplib/
http://dotnetzip.codeplex.com/
I prefer #ziplib, but both are well documented and widely spread.
Since .NET Framework 4.5, you can use the built-in ZipFile class (In the System.IO.Compression namespace).
public void ZipFiles(string[] filePaths, string zipFilePath)
{
ZipArchive zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create);
foreach (string file in filePaths)
{
zipArchive.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
}
zipArchive.Dispose();
}
Take a look at the FileSelectionManager library here: www.fileselectionmanager.com
First you have to add File Selection Manager DLL to your project
Here is an example for zipping:
class Program
{
static void Main(string[] args)
{
String directory = #"C:\images";
String destinationDiretory = #"c:\zip_files";
String zipFileName = "container.zip";
Boolean recursive = true;
Boolean overWrite = true;
String condition = "Name Contains \"uni\"";
FSM FSManager = new FSM();
/* creates zipped file containing selected files */
FSManager.Zip(directory,recursive,condition,destinationDirectory,zipFileName,overWrite);
Console.WriteLine("Involved Files: {0} - Affected Files: {1} ",
FSManager.InvolvedFiles,
FSManager.AffectedFiles);
foreach(FileInfo file in FSManager.SelectedFiles)
{
Console.WriteLine("{0} - {1} - {2} - {3} - {4} Bytes",
file.DirectoryName,
file.Name,
file.Extension,
file.CreationTime,
file.Length);
}
}
}
Here is an example for unzipping:
class Program
{
static void Main(string[] args)
{
String destinationDiretory = #"c:\zip_files";
String zipFileName = "container.zip";
Boolean unZipWithDirectoryStructure = true;
FSM FSManager = new FSM();
/* Unzips files with or without their directory structure */
FSManager.Unzip(zipFileName,
destinationDirectory,
unZipWithDirectoryStructure);
}
}
Hope it helps.
I use the dll fileselectionmanager to compress and decompress files and folders, it has worked properly in my project. You can see example in your web http://www.fileselectionmanager.com/#Zipping and Unzipping files
and documentation http://www.fileselectionmanager.com/file_selection_manager_documentation