how to zip all files with asp.net 3.5 - asp.net-3.5

i 'm .net developer. i want to Zip all files and make a one zip file with this technique.
ZipFile multipleFilesAsZipFile = new ZipFile();
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".zip");
Response.ContentType = "application/zip";
for (int i = 0; i < filename.Length; i++)
{
string filePath = Server.MapPath("~/PostFiles/" + filename[i]);
multipleFilesAsZipFile.AddFile(filePath, string.Empty);
}
multipleFilesAsZipFile.Save(Response.OutputStream);
how ever for making this Zip i use third party library Ionic.
all files are ziped successfully but not extracted to client desktop. is there problem with my code. or this library that i'm using has been expired.
Is there free full version .net compatible library to zip all files.

Use SharpZipLib:
Nuget Package
Install-Package SharpZipLib
OR Download here
http://www.icsharpcode.net/OpenSource/SharpZipLib/
Snippet from examples:
private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) {
string[] files = Directory.GetFiles(path);
foreach (string filename in files) {
FileInfo fi = new FileInfo(filename);
string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder
entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
ZipEntry newEntry = new ZipEntry(entryName);
newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity
// Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256.
// A password on the ZipOutputStream is required if using AES.
// newEntry.AESKeySize = 256;
// To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
// you need to do one of the following: Specify UseZip64.Off, or set the Size.
// If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
// but the zip will be in Zip64 format which not all utilities can understand.
// zipStream.UseZip64 = UseZip64.Off;
newEntry.Size = fi.Length;
zipStream.PutNextEntry(newEntry);
// Zip the file in buffered chunks
// the "using" will close the stream even if an exception occurs
byte[ ] buffer = new byte[4096];
using (FileStream streamReader = File.OpenRead(filename)) {
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
string[ ] folders = Directory.GetDirectories(path);
foreach (string folder in folders) {
CompressFolder(folder, zipStream, folderOffset);
}
}
Taken from : https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples
Works awesome!

Related

C# Read binary file as string then save as binary file

I've been given string data (stored in a database) where the originator read binary tiff files as a string using something like (they actually used the VB FileSystemObject):
var txt = File.ReadAllText(#"c:\some_image.tiff");
I need to re-create the original tiff files. I've tried looping through all encodings with:
var txt = File.ReadAllText(#"c:\test\some_image.tiff");
var encodings = Encoding.GetEncodings();
for (var i = 0; i < encodings.Length; i++)
{
File.WriteAllBytes(#"c:\test\some_image_" + i + ".tiff", encodings[i].GetEncoding().GetBytes(txt));
}
but to no avail.

Get upload filename in eclipse using servlet

I have an application that uploads a file. I need to pass this file into another program but for that I need the file name only. Is there any simple code for that, using only Java or a servlet procedure?
while (files.hasMoreElements())
{
name = (String)files.nextElement();
type = multipartRequest.getContentType(name);
filename = multipartRequest.getFilesystemName(name);
originalFilename = multipartRequest.getOriginalFileName(name);
//extract the file extension - this can be use to reject a
//undesired file extension
extension1 = filename.substring
(filename.length() - 4, filename.length());
extension2 = originalFilename.substring
(originalFilename.length() - 4, originalFilename.length());
//return a File object for the specified uploaded file
File currentFile = multipartRequest.getFile(name);
//InputStream inputStream = new BufferedInputStream
(new FileInputStream(currentFile));
if(currentFile == null) {
out.println("There is no file selected!");
return;
}
There's a method in apache commons-io to get the file's extension. There's also guava Files class, with its getFileExtension method.

Upload Servlet with custom file keys

I have built a Server that you can upload files to and download, using Eclipse, servlet and jsp, it's all very new to me. (more info).
Currently the upload system works with the file's name. I want to programmatically assign each file a random key. And with that key the user can download the file. That means saving the data in a config file or something like : test.txt(file) fdjrke432(filekey). And when the user inputs the filekey the servlet will pass the file for download.
I have tried using a random string generator and renameTo(), for this. But it doesn't work the first time, only when I upload the same file again does it work. And this system is flawed, the user will receive the file "fdjrke432" instead of test.txt, their content is the same but you can see the problem.
Any thoughts, suggestions or solutions for my problem?
Well Sebek, I'm glad you asked!! This is quite an interesting one, there is no MAGIC way to do this. The answer is indeed to rename the file you uploaded. But I suggest adding the random string before the name of the file; like : fdjrke432test.txt.
Try this:
filekey= RenameRandom();
File renamedUploadFile = new File(uploadFolder + File.separator+ filekey+ fileName);
item.write(renamedUploadFile);
//remember to give the user the filekey
with
public String RenameRandom()
{
final int LENGTH = 8;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random()*26)+97));
}
System.out.println(sb.toString());
return sb.toString();
}
To delete or download the file from the server you will need to locate it, the user will input the key, you just need to search the upload folder for a file that begins with that key:
filekey= request.getParameter("filekey");
File f = new File(getServletContext().getRealPath("") + File.separator+"data");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(filekey);
}
});
String newfilename = matchingFiles[0].getName();
// now delete or download newfilename

j2me netbeans - parallel data transfer (outline idea required)

I am new to j2me Mobile Applications. I have a college project to be done within a month. I need some basic idea of how it can be done. I am using Netbeans 6.8 j2me platform.
I have to create source, destination and many intermediate nodes(mobile phones). A file has to be sent(am using Bluetooth) from source to destination via several intermediate nodes. The file can be split into chunks and can also be sub-divided at any level.
http://imageshack.us/photo/my-images/692/parallelism.jpg/
This is how it should work:
Initially, the source sends simple objects of a Class(present in all nodes) to destination via several paths. Every node will be updating the object by including its Bluetooth address and passes it to the next node. When it reaches the destination, the same object is sent back to the source. The source identifies some of the optimal paths and uses them for file transfer.
The source splits the file and send them to the nearest nodes. The intermediate nodes can also split and send the divided parts.
When all the parts reach the destination, they are joined and the file is reconstructed.
I created separate netbeans project for source, destination and intermediate node.
Splitting : I did splitting successfully by converting the file into byte array and creating files using File connection & outputstream
public void splitfiles(int len)
{
String url="file:///root1/testfile.jpg";
// int len = 102400;
byte buffer[] = new byte[size];
int count = 0;
try
{
FileConnection fconi = (FileConnection)Connector.open(url,Connector.READ);
InputStream fis = fconi.openInputStream();
while (true)
{
int i = fis.read(buffer, 0, len); //creating byte array of size "len" bytes
if (i == -1)
break;
++count;
String filename ="file:///root1/testfile.part" + count;
FileConnection fcono = (FileConnection)Connector.open(filename,Connector.READ_WRITE);
if (!fcono.exists())
fcono.create();
OutputStream fos = fcono.openOutputStream();
fos.write(buffer, 0, i); //creating files out of byte array "buffer"
fos.close();
fcono.close();
}
}
catch(Exception e)
{ }
}
Please tell me how to rejoin the files.(I rejoined them using java class "RandomAcessFile" which is not present in j2me).
I tried in the following way
while(number of chunks)
{
read a single file in inputstream (files are read one after the other)
copy it to a byte array and flush inputstream
write it to ouputstream
}
copy outputstream to a file
flush outputstream
Please give me some idea about
how to rejoin the chunks in j2me
How to pass object of a class via bluetooth

How to read a directory with using InputStream in eclipse plugin developement

I'm developing an eclipse plug-in and I need to traverse a directory and whole content of the directory. I found the method which reads a file in plug-in (bundleresource) as InputStream.
InputStream stream = Activator.class.getResourceAsStream("/dir1/dir2/file.ext");
this method works for files only. I need a way to read directories, list subdirectories and files like File.io.
Thanks.
Do you want to read a resource directory of your plugin? Otherwise you have to traverse a directory and open one stream per file:
String path = "c:\\temp\\";
File directory = new File(path);
if (directory.isDirectory()) {
String[] list = directory.list();
for (String entry : list) {
String absolutePath = path + entry;
System.out.println("processing " + absolutePath);
File file = new File(absolutePath);
if (file.isFile()) {
FileInputStream stream = new FileInputStream(file);
// use stream
stream.close();
}
}
}
If you want to traverse subdirectories as well you should wrap this into a recursive method, check if file is a directory and call the recursive method in this case.