zip not extracting created using DotnetZip (Ionic.zip)(1.10.1) - asp.net

I am using DotNetZip.dll(1.10.1) for creating zip files(media files), Files get zipped but when I try to extract it using WinRaR or with windows extract folder option, I am getting "the archive is unknown format or damaged"
List<string> fileNames = new List<string>();
using (ZipFile zip = new ZipFile())
{
//zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
zip.ParallelDeflateThreshold = -1;
zip.Encryption = EncryptionAlgorithm.None;
zip.AddFiles(fileNames.AsEnumerable(),"");
zip.Save(zipSavePath);
}
CRC32 of zipped file is 00000000.
I am using .net framework 4.0 and web forms.
Can you please let me what wrong am I doing
Thanks

Related

Save an Image with a new file name [ImageSharp]

I have upgraded my project from .net framework to .net 6 (core). In my project, there are many places where Bitmap is used. I have read in the microsoft documentations that System.Drawing.Common will only support the Windows platform and even after adding the EnableUnixSupport configuration, it will not be supported in net7.So, now I am using ImageSharp.Web. I have the scenario where I save a file as Image (the format is .tiff) then I read from that path as bitmap and save as PNG ( due to some business rule)
Following is the line of code I am trying change:
Bitmap.FromFile(completePath).Save(pngPath, ImageFormat.Png);
This is the code I have converted into. The only issue is how to save as a new file name as the Tiff file has tiff in the file name.
string extension = _GetExtension(img.ContentType);
if (extension == Constants.TiffExtension)
{
fileName = fileName.Replace(Constants.TiffExtension, "PNG");
using (var outputStream = new FileStream(completePath, FileMode.CreateNew))
{
var image = SixLabors.ImageSharp.Image.Load(completePath);
image.SaveAsync(outputStream, new PngEncoder()); //how to save new file name?
}
}
You can use the image.Save(fileName); overload to save a image to a file. The file name overload that takes just a path will automatically choose the correct encoder based on the file extension.
I was using the ImageSharp.Web package while the one I needed was the basic ImageSharp package. Special thanks to #James South for correcting me and #tocsoft for the guidance.
I have fixed it by the following code which is working:
if (extension == Constants.Conversion.TiffExtension)
{
using (SixLabors.ImageSharp.Image image = SixLabors.ImageSharp.Image.Load(completePath))
{
string pngPath = completePath.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
image.Save(pngPath);
fileName = fileName.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
}
}

Asp.net Multiple files download

Im trying to search and download the files uploaded to the database,I can able to retrieve the files from the database.
Downloading single file works but cant download multiple files at a time,I have read about downloading as a zip file,Can anyone help??????
using (sampledbase dbcontext = new sampledbase ())
{
ZipFile zip = new ZipFile();
long id = Convert.ToInt64(Request.QueryString["id"]);
System.Nullable<long> fileid = id;
var query = dbcontext.searchfile(ref fileid );
foreach (var i in query)
{
byte[] binarydata = i.Data.ToArray();
Response.AddHeader("content-disposition", string.Format("attachment; filename =\"{0}\"", i.Name));
Response.BinaryWrite(binarydata);
Response.ContentType = i.ContentType;
Response.End();
}
}
I see that you are using ZipFile so you are in the right direction. In order to zip your files, you can save your files in a directory and zip the directory using this code :
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
ZipFile.CreateFromDirectory(startPath, zipPath);
In your case, look at the data type returned by dbcontext.searchfile() and save the content to a directory using something like StreamWriter. Looking at your code, the type seems to be a byte[], you can see this link to learn how to save the bytes in a file : Write bytes to file
Another solution is to zip directly the bytes[] : Create zip file from byte[]

excel data from asp

i have made a list of folders from my directory, to show as html.
What i want is to be able to read and write in excel.
now what am strugleing to do is put this code to get it as .xlsx. i have a excel file in my computer and want all the directories to go in that file..
I have been told EPPlus is the best solution. but am not sure how to implement this in the above code so my directories comes in excel rather than html.
any ideas/direction would be really helpful
If you want to go the route of EPPlus, first thing you need to do is add the EPPlus package to your solution. This can be achieved by doing one of the following:
Opening up NuGet, searching for EPPlus in the gallery and installing it
Opening up your Package Manager Console and typing Install-Package EPPlus
Downloading the dll file and manually adding a reference to it in your project.
Then, in your code:
using OfficeOpenXml;
using System.IO;
using System.Linq;
namespace TestConsole {
class Program {
static void Main(string[] args) {
string[] directoryList = System.IO.Directory.GetDirectories(#"C:\Users\bblack\Temp\TestDirectories\");
using (Stream file = new FileStream(#"C:\Users\bblack\Temp\testexcelfile.xlsx", FileMode.Create))
using (ExcelPackage xl = new ExcelPackage(file)) {
ExcelWorksheet sheet = xl.Workbook.Worksheets.Add("Sheet1");
for (int i = 1; i < directoryList.Count(); i++)
sheet.Cells[i, 1].Value = directoryList[i];
xl.Save();
}
}
}
}
This
Gets all the directories in the address provided to it.
Creates a new FileStream where you want your Excel file to be
Creates a new ExcelPackage based off of the FileStream
Adds a new worksheet (there are zero by default) to the workbook in the ExcelPackage
Iterates through directoryList, and for each string in there puts the value in a new cell
it is important to note, that worksheet cell indexes are not zero-based, they start with a base index of 1
edit Woops, forgot to close the stream, use this updated answer.

Returning Multiple Files from MVC Action

So I've got an MVC 3 application that has a couple places where a text file gets generated and returned in an action using:
return File(System.Text.Encoding.UTF8.GetBytes(someString),
"text/plain", "Filename.extension");
and this works fabulously. Now i've got a situation where I'm trying to return a pair of files in a similar fashion. On the view, i have an action link like "Click here to get those 2 files" and i'd like both files to be downloaded much like the single file is downloaded in the above code snippet.
How can I achieve this? Been searching around quite a bit and haven't even seen this question posed anywhere...
Building on Yogendra Singh's idea and using DotNetZip:
var outputStream = new MemoryStream();
using (var zip = new ZipFile())
{
zip.AddEntry("file1.txt", "content1");
zip.AddEntry("file2.txt", "content2");
zip.Save(outputStream);
}
outputStream.Position = 0;
return File(outputStream, "application/zip", "filename.zip");
Update 2019/04/10:
As #Alex pointed out, zipping is supported natively since .NET Framework 4.5, from JitBit and others:
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var file1 = archive.CreateEntry("file1.txt");
using (var streamWriter = new StreamWriter(file1.Open()))
{
streamWriter.Write("content1");
}
var file2 = archive.CreateEntry("file2.txt");
using (var streamWriter = new StreamWriter(file2.Open()))
{
streamWriter.Write("content2");
}
}
return File(memoryStream.ToArray(), "application/zip", "Images.zip")
}
Sorry for bumping an old question but...
Another alternative would be to initiate multiple file downloads using JavaScript, and serve files in two different Action Methods on ASP.NET's side.
You're saying you have a link:
On the view, i have an action link like "Click here to get those 2
files"
So make this link like this:
Click to get 2 files
<script src="download.js"></script>
I'm using download.js script found here but you can find plenty of different other options, see this SO question: starting file download with JavaScript for example
I would advice to create a zip file to include both the files using steps(ALGORITHM):
Create a Zip file and add the desired files into the zip
Return the zip file having all desired files from the action
Java Syntax (Just for understanding)
FileOutputStream fos = new FileOutputStream("downloadFile.zip");
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
zos.putNextEntry(new ZipEntry("Filename1.extension"+));
//write data in FileName1.extension
zos.write(contentBuffer1, 0, len);
zos.putNextEntry(new ZipEntry("Filename2.extension"));
//write data in FileName2.extension
zos.write(contentBuffer2, 0, len);
//write other files.....
zos.close();
Once zip file is created, return the newly created zip file to download.
return File("downloadFile.zip");
.DOT Net Equivalent using DotNetZip
var os = new MemoryStream();
using (var zip = new ZipFile())
{
//write the first file into the zip
zip.AddEntry("file1.txt", "content1");
//write the second file into the zip
zip.AddEntry("file2.txt", "content2");
//write other files.....
zip.Save(os);
}
outputStream.Position = 0;
return File(outputStream, "application/zip", "filename.zip");
Hope this helps!
Look at this SO solution: MVC Streaming Zip File
The advantage of this solution is that it streams the file to the client.
I just implemented this solution a couple of days ago and it worked fantastic.

The given path's format is not supported

I am getting the following error while uploading the file from my local drive.
The given path's format is not supported.
The code is given.
Please tell me what changes I have to make.
string file0 = MapPathReverse(FileUpload1.PostedFile.FileName);// Get virtual path
string conversationFileSource = Server.MapPath(file0);
StreamReader file = new StreamReader(conversationFileSource);
If you want to access the input stream of the uploaded file:
using (StreamReader reader = new StreamReader(FileUpload1.PostedFile.InputStream))
{
...
}
If you want to save the uploaded file on some folder on your server:
var uploadsFolder = Server.MapPath("~/uploads");
var file = Path.Combine(uploadsFolder, Path.GetFileName(FileUpload1.PostedFile.FileName));
FileUpload1.PostedFile.SaveAs(file);

Resources