In my requirement I am converting docx to images its working fine but I need to store that converted multiple images into Zip file. Zip file was created successfully but Images are not opening it show corrupted/damage. Please try to help me to solve this solution. please refer my below total code. I used using Ionic.Zip; for creating a zip file.
//Opens the word document and fetch each page and converts to image
foreach (Microsoft.Office.Interop.Word.Window window in doc1.Windows)
{
foreach (Microsoft.Office.Interop.Word.Pane pane in window.Panes)
{
using (var zip = new ZipFile())
{
var pngTarget = "";
for (var i = 1; i <= pane.Pages.Count; i++)
{
var page = pane.Pages[i];
var bits = page.EnhMetaFileBits;
var target = Path.Combine(startupPath.Split('.')[0], string.Format("{1}_page_{0}", i, startupPath.Split('.')[0]));
try
{
using (var ms = new MemoryStream((byte[])(bits)))
{
var image = System.Drawing.Image.FromStream(ms);
pngTarget = Path.ChangeExtension(target, "png");
image.Save(pngTarget, ImageFormat.Png);
zip.AddEntry(pngTarget, "Img");
}
}
catch (System.Exception ex)
{ }
}
// CREATE A FILE USING A STRING.
// THE FILE WILL BE STORED INSIDE THE ZIP FILE.
// ZIP THE FOLDER WITH THE FILES IN IT.
//zip.AddFiles(Directory.GetFiles(#"c:\\users\\chaitanya_t\\Downloads\\"), "Images");
zip.Save(#"c:\\users\\chaitanya_t\\Downloads\\encoded.zip"); // SAVE THE ZIP FILE.
}
}
}
Try setting the stream position at the begin of the stream before processing:
using (var ms = new MemoryStream((byte[])(bits))){
ms.Position = 0; // Set stream position at the begin of the stream
var image = System.Drawing.Image.FromStream(ms);
pngTarget = Path.ChangeExtension(target, "png");
image.Save(pngTarget, ImageFormat.Png);
zip.AddEntry(pngTarget, ms.ToArray());
}
Related
I want to save multiple files in one Zip file on my disc. This Zip is created but his type is "Compressed (zipped) Folder" and is impossible to open. Error: "Windows cannot open the folder. The Compressed (zipped) Folder 'path' is invalid. Can I make it normal .Zip file somehow?
int i = 0;
await using var ms = new MemoryStream();
{
using var archive = new ZipArchive(ms, ZipArchiveMode.Create, true);
{
foreach (var s in stepwiseData)
{
//streamWriter.Write(s);
var entry = archive.CreateEntry($"Name {i.ToString()}");
i++;
using (BinaryWriter writer = new BinaryWriter(entry.Open()))
{
writer.Write(s.ToArray());
}
}
var folder = #"C:\Temp\test\";
var fileName = "TestName.zip";
var fullPath = folder + fileName;
var bytes = ms.ToArray();
File.WriteAllBytes(fullPath, bytes);
}
}
var getImage = model.Document.Get().Where(x => x.ReferenceNo == ReferenceNo && x.ChecklistId == 225).FirstOrDefault();
var Imagefilename = path + "\\" + ReferenceNo.Replace("/", "_") + "IdentityPhoto.Jpg";
var filebytes = ConvertToBytes(getImage.FileData);
using (var filestream = new FileStream(Imagefilename, FileMode.Create, FileAccess.Write))
{
filestream.Write(filebytes, 0, filebytes.Length);
filestream.Close();
filestream.Dispose();
}
using (Spire.Doc.Document document = new Spire.Doc.Document(#OpenTemplate))
{
Spire.Doc.Section section = document.Sections[0];
System.Drawing.Bitmap p = new Bitmap(System.Drawing.Image.FromFile(#Imagefilename));
// p.RotateFlip(RotateFlipType.Rotate90FlipX);
Spire.Doc.Fields.DocPicture picture = document.Sections[0].Paragraphs[0].AppendPicture(p);
// set image's position
picture.HorizontalPosition = 370.0F;
picture.VerticalPosition = 480.0F;
// set image's size
picture.Width = 80;
picture.Height = 80;
// set textWrappingStyle with image;
picture.TextWrappingStyle = Spire.Doc.Documents.TextWrappingStyle.Through;
// Save doc file.
document.SaveToFile(#Demo, Spire.Doc.FileFormat.Docx);
p.Dispose();
document.Dispose();
document.Close();
}
// Trying to delete this file
try
{
if (File.Exists(Imagefilename))
{
File.Delete(Imagefilename);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
Using a Word document as template, image is retrieved from database. It is stored on the C drive, the image at that location is then being used and inserted into a word document.
When trying to delete the image from the drive after use it keeps on throwing an error:
Error message "process cannot access the file because it is being used by another process"
I have tried using .Dispose and .Close functions and using statements. I have tried Directory.Delete but nothing seems to be working.
I am attempting to download a bunch of files that I am zipping up(archiving) via ZipoutputStream.
using (var zipStream = new ZipOutputStream(outputMemStream))
{
foreach (var documentIdString in documentUniqueIdentifiers)
{
...
var blockBlob = container.GetBlockBlobReference(documentId.ToString());
var fileMemoryStream = new MemoryStream();
blockBlob.DownloadToStream(fileMemoryStream);
zipStream.SetLevel(3);
fileMemoryStream.Position = 0;
ZipEntry newEntry = new ZipEntry(document.FileName);
newEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(newEntry);
fileMemoryStream.Seek(0, SeekOrigin.Begin);
StreamUtils.Copy(fileMemoryStream, zipStream, new byte[4096]);
zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream.
}
outputMemStream.Seek(0, SeekOrigin.Begin);
return outputMemStream;
}
In my controller I am returning the following code that should download the Zip file i created in the previous example. The controller actions downloads the file as it should in the browser, but the Archived File is empty. I can see the content length populated returning from the method above...
file.Seek(0, SeekOrigin.Begin);
return File(file, "application/octet-stream", "Archive.zip");
Does anyone have any idea why my file that is returned by my controller is empty or corrupt?
I believe you need to close your entries and your final zip stream. You should also using and dispose all of your streams. Try this:
using (var zipStream = new ZipOutputStream(outputMemStream))
{
zipStream.IsStreamOwner = false;
// Set compression level
zipStream.SetLevel(3);
foreach (var documentIdString in documentUniqueIdentifiers)
{
...
var blockBlob = container.GetBlockBlobReference(documentId.ToString());
using (var fileMemoryStream = new MemoryStream())
{
// Populate stream with bytes
blockBlob.DownloadToStream(fileMemoryStream);
// Create zip entry and set date
ZipEntry newEntry = new ZipEntry(document.FileName);
newEntry.DateTime = DateTime.Now;
// Put entry RECORD, not actual data
zipStream.PutNextEntry(newEntry);
// Copy date to zip RECORD
StreamUtils.Copy(fileMemoryStream, zipStream, new byte[4096]);
// Mark this RECORD closed in the zip
zipStream.CloseEntry();
}
}
// Close the zip stream, parent stays open due to !IsStreamOwner
zipStream.Close();
outputMemStream.Seek(0, SeekOrigin.Begin);
return outputMemStream;
}
EDIT - you should remove:
// Reset position of stream
fileMemoryStream.Position = 0;
Pretty sure that's the problem.
Inside my app, I am trying to download about 180 small audio files all at once. I tried the BackgroundTransferService, but it does not seem stable with so many small files. So, now I am downloading a ZIP of all those audio and want extract them in "audio" folder. I tried the method in this thread:
How to unzip files in Windows Phone 8
But I get this error: 'System.IO.IOException' occurred in mscorlib.ni.dll... in the following code. How can I overcome this issue?
while (reader.ReadInt32() != 101010256)
{
reader.BaseStream.Seek(-5, SeekOrigin.Current); // this line causes error
}...
Also, where do I need to place this code and where do I give it the destination directory?
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(#"audio.rar", FileMode.Open, FileAccess.ReadWrite))
{
UnZipper unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip())
{
string FileName = filename;
}
}
Use Silverlight SharpZipLib. Add SharpZipLib.WindowsPhone7.dll to your project (works on WP8 silverlight also).
private void Unzip()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
ZipEntry entry;
int size;
byte[] data = new byte[2048];
using (ZipInputStream zip = new ZipInputStream(store.OpenFile("YourZipFile.zip", FileMode.Open)))
{
// retrieve each file/folder
while ((entry = zip.GetNextEntry()) != null)
{
if (!entry.IsFile)
continue;
// if file name is music/rock/new.mp3, we need only new.mp3
// also you must make sure file name doesn't have unsupported chars like /,\,etc.
int index = entry.Name.LastIndexOf('/');
string name = entry.Name.Substring(index + 1);
// create file in isolated storage
using (var writer = store.OpenFile(name, FileMode.Create))
{
while (true)
{
size = zip.Read(data, 0, data.Length);
if (size > 0)
writer.Write(data, 0, size);
else
break;
}
}
}
}
}
}
There are several 3rd party libraries in order to extract ZIP files in WP8 like the ZipLib which you can download from # http://slsharpziplib.codeplex.com/
however DotNetZip a parent ZipLib and much more stable.
Here is a sample code. Not checked if it works, but this is how you go at it.
ZipFile zip = ZipFile.Read(ZipFileToUnzip);
foreach (ZipEntry ent in zip)
{
ent.Extract(DirectoryWhereToUnizp, ExtractExistingFileAction.OverwriteSilently);
}
I have just solved this. what you can do is use this method and your file will go save to isolated storage in proper folder structure as present in your zip file. you can change according to your need where you want to store the data.
I have just read a sample.zip file. From your app folder.
private async Task UnZipFile()
{
var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
using (var fileStream = Application.GetResourceStream(new Uri("sample.zip", UriKind.Relative)).Stream)
{
var unzip = new UnZipper(fileStream);
foreach (string filename in unzip.FileNamesInZip)
{
if (!string.IsNullOrEmpty(filename))
{
if (filename.Any(m => m.Equals('/')))
{
myIsolatedStorage.CreateDirectory(filename.Substring(0, filename.LastIndexOfAny(new char[] { '/' })));
}
//save file entry to storage
using (var streamWriter =
new StreamWriter(new IsolatedStorageFileStream(filename,
FileMode.Create,
FileAccess.ReadWrite,
myIsolatedStorage)))
{
streamWriter.Write(unzip.GetFileStream(filename));
}
}
}
}
}
cheers :)
I have a HttpPostedFile object and after the file gets uploaded locally onto the server, i want to move that temp file into a document library in sharepoint. Here is my code:
private void UploadWholeFile(HttpContext context, List<FilesStatus> statuses) {
for (int i = 0; i < context.Request.Files.Count; i++) {
HttpPostedFile file = context.Request.Files[i];
file.SaveAs(ingestPath + Path.GetFileName(file.FileName));
string fileName = Path.GetFileName(file.FileName);
}
Can anyone give me some example code for this? I have found a tutorial for Streams, but not quite sure if it would work the same in my situation
Replace the two lines starting with file.SaveAs with the following:
var myDocumentLibrary = SPContext.Current.Web.Folders["MyDocumentLibrary"];
var myFile = myDocumentLibrary.Files.Add(file.Name, file.FileContent, true);
I have a code sample for you that comes in parts:
Here is code that gets the Files content into a byte array buffer:
var file = (HttpPostedFileBase)Request.Files[0];
var buffer = new byte[file.ContentLength];
file.InputStream.Read(buffer, 0, file.ContentLength);
var root = HttpContext.Current.Server.MapPath(#"~/_temp");
var temp_file_name = "somefilename";
var path = Path.Combine(root, temp_file_name);
using (var fs = new FileStream(path, FileMode.Create))
{
using (var br = new BinaryWriter(fs))
{
br.Write(buffer);
}
}