How to zip and unzip folders and its sub folders in Silverlight? - zip

I have a Windows Phone application. I am using SharpZipLib to zip folders and its sub folders. This is zipping only the folder but the data inside the folders is not getting zipped. Can anyone guide me how to do this?
My code:
private void btnZip_Click(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (string filename in appStore.GetFileNames(directoryName + "/" + "*.txt"))
{
GetCompressedByteArray(filename);
}
textBlock2.Text = "Created file has Zipped Successfully";
}
}
public byte[] GetCompressedByteArray(string content)
{
byte[] compressedResult;
using (MemoryStream zippedMemoryStream = new MemoryStream())
{
using (ZipOutputStream zipOutputStream = new ZipOutputStream(zippedMemoryStream))
{
zipOutputStream.SetLevel(9);
byte[] buffer;
using (MemoryStream file = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
buffer = new byte[file.Length];
file.Read(buffer, 0, buffer.Length);
}
ZipEntry entry = new ZipEntry(content);
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(buffer, 0, buffer.Length);
zipOutputStream.Finish();
}
compressedResult = zippedMemoryStream.ToArray();
}
WriteToIsolatedStorage(compressedResult);
return compressedResult;
}
public void WriteToIsolatedStorage(byte[] compressedBytes)
{
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
appStore.CreateDirectory(ZipFolder);
using (IsolatedStorageFileStream zipTemplateStream = new IsolatedStorageFileStream(ZipFolder+"/"+directoryName + ".zip", FileMode.OpenOrCreate, appStore))
using (BinaryWriter streamWriter = new BinaryWriter(zipTemplateStream))
{
streamWriter.Write(compressedBytes);
}
}

I think you'll find this guide helpful.
An excerpt from the above link
The ZipFile object provides a method called AddDirectory() that
accepts a parameter directoryName. The problem with this method is
that it doesn't add the files inside the specified directory but
instead just creates a directory inside the zip file. To make this
work, you need to get the files inside that directory by looping thru
all objects in that directory and adding them one at a time. I was
able to accomplish this task by creating a recursive function that
drills through the whole directory structure of the folder you want to
zip. Below is a snippet of the function.
I guess you too are facing the same problem where the folder is added to the zip file, but the contents and sub folders are not zipped.
Hope this helps.

Have a look over here for a code sample on how to use SharpZipLib to zip a root folder including nested folders.

Related

Upload BASE64 binary file to SharePoint document library

I have been looking for ways to upload BASE64 binary files days and I am stuck.
First of all a do not know how to convert BASE64 binary file to array buffer, blob, ... Everything is about BASE64 string but I have BASE64 binary file.
Do you have any solution?
You need to convert this Base64 string to byte array. C# Programming provide several approaches to do this without trouble. Following Upload large files sample SharePoint Add-in and Convert.FromBase64String(String) Method, both at Microsoft Docs, the final code that meet your requirements will be like this:
//This approach is useful for short files, less than 2Mb:
public void UploadFileContentFromBase64(ClientContext ctx, string libraryName, string fileName, string base64Str)
{
Web web = ctx.Web;
// Ensure that target library exists. Create if it is missing.
if (!LibraryExists(ctx, web, libraryName))
{
CreateLibrary(ctx, web, libraryName);
}
FileCreationInformation newFile = new FileCreationInformation();
// The next line of code causes an exception to be thrown for files larger than 2 MB.
newFile.Content = Convert.FromBase64String(base64Str);
newFile.Url = fileName;
// Get instances to the given library.
List docs = web.Lists.GetByTitle(libraryName);
// Add file to the library.
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
}
//This other approach provides you to Upload large files, more than 2Mb:
public void UploadDocumentContentStreamFromBase64(ClientContext ctx, string libraryName, string fileName, string base64Str)
{
Web web = ctx.Web;
// Ensure that the target library exists. Create it if it is missing.
if (!LibraryExists(ctx, web, libraryName))
{
CreateLibrary(ctx, web, libraryName);
}
byte[] fileContent = Convert.FromBase64String(base64Str);
using (MemoryStream memStream = new MemoryStream(fileContent))
{
FileCreationInformation flciNewFile = new FileCreationInformation();
// This is the key difference for the first case - using ContentStream property
flciNewFile.ContentStream = memStream;
flciNewFile.Url = fileName;
flciNewFile.Overwrite = true;
List docs = web.Lists.GetByTitle(libraryName);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
}
}

Kentico 11 - MediaFileInfoProvider.DeleteMediaFileInfo Not Deleting

MediaFileInfo updateFile = MediaFileInfoProvider.GetMediaFileInfo(library.LibraryID, file.Name);
The above line of code is not removing the file from the media library as I expected. This is for a Scheduled Task in Kentico 11 MVC. The new file does get created and is renamed by the System to prevent conflicts.
I would like to delete the existing file before importing the updated version of the file. I would even be satisfied if the new file overwrote the existing file.
public void UpdateMediaFile(MediaLibraryInfo library, string fileName, string importPath)
{
//LumberMarketReport.pdf and PanelMarketReport.pdf
if (library != null)
{
// Prepares a path to a local file
string filePath = fileName;
// Prepares a CMS.IO.FileInfo object representing the local file
CMS.IO.FileInfo file = CMS.IO.FileInfo.New(filePath);
if (file != null)
{
#region "Delete Existing"
MediaFileInfo updateFile = MediaFileInfoProvider.GetMediaFileInfo(library.LibraryID, file.Name);
if (updateFile != null)
{
MediaFileInfoProvider.DeleteMediaFileInfo(updateFile);
}
#endregion
#region "Create File"
// Creates a new media library file object
MediaFileInfo mediaFile = new MediaFileInfo(filePath, library.LibraryID);
// Sets the media library file properties
mediaFile.FileName = file.Name;
mediaFile.FileDescription = "This file was added through the API.";
mediaFile.FilePath = "/"; // Sets the path within the media library's folder structure
mediaFile.FileExtension = file.Extension;
mediaFile.FileMimeType = MimeTypeHelper.GetMimetype(file.Extension);
mediaFile.FileSiteID = SiteContext.CurrentSiteID;
mediaFile.FileLibraryID = library.LibraryID;
mediaFile.FileSize = file.Length;
if (file.Name == "PanelMarketReport.pdf")
{
mediaFile.FileTitle = "Panel Market Report";
mediaFile.SetValue("FileCategoryID", 19);
}
else if (file.Name == "LumberMarketReport.pdf")
{
mediaFile.FileTitle = "Lumber Market Report";
mediaFile.SetValue("FileCategoryID", 57);
}
// Saves the media library file
MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
#endregion
}
}
}
I would add logging to make sure your code is getting hit. Make sure updatefile isn't null. I think you have to pass in the file path in the media library and not just the name.
If I am not mistaken MediaFileInfoProvider.DeleteMediaFileInfo will remove a record from DB but not physically delete the file, so you need to call CMS.IO.FileInfo.Delete(filePath) to delete it from disk.

Emgu CV C# Exception creating tesseract object

I can access all emgu libraries. VS finds the libraries and using Emgu.CV.OCR returns no errors.
When I try to create a Tesseract object, Program.cs throws a FileLoadException. in System.Windows.Forms.dll.
Removing the line of code that creates a tesseract lets the program run fine.
I have tried copying tessdata to my debug file and that also has not worked.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
Tesseract _ocr;
_ocr = new Tesseract(#"tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);
OpenFileDialog Openfile = new OpenFileDialog();
if (Openfile.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
pictureBox1.Image = My_Image.ToBitmap();
}
}
I fiddled with the same problem for a while; now I got it.
First, make sure you have the following using directives (you might need to download Emgu.CV via NuGet):
using Emgu.CV;
using Emgu.CV.OCR;
using System.Reflection;
using System.IO;
using System.Drawing;
Then, make sure you have the most up-to-date tessdata on board. If not, navigate to github and download it (click "Clone or Download" and select "Download ZIP File"). You should then unzip the file and rename the folder "tessdata-master" to "tessdata." Copy this folder to the place where your binary lives (the assembly location).
Lastly, assign the correct path, and you're ready to do OCR!
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\";
var _ocr = new Tesseract(path, "eng", OcrEngineMode.Default);
_ocr.SetImage(yourImage);
_ocr.Recognize();
var result = _ocr.GetCharacters();
First you need to check your project References . Is there "Emgu.CV.OCR" library if not kindly add it first. Then try the following code may it will work for you.
private void button1_Click(object sender, EventArgs e)
{
Tesseract _ocr;
_ocr = new Tesseract(#"C:\Emgu\emgucv-windows-universal-cuda 2.9.0.1922\Emgu.CV.OCR\tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);//first Parameter set your path ..complete path like i did
_ocr.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopkrstuvwxyz");
OpenFileDialog Openfile = new OpenFileDialog();
if (Openfile.ShowDialog() == DialogResult.OK)
{
Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(Openfile.FileName);
pictureBox1.Image = My_Image.ToBitmap();
}
}

File path working in NetBeans but not in built JAR file

I am trying to copy file from classpath to user specified location. However, While running program in netbeans, file path works correctly and file gets copied but when I build a jar file and try the same, it doesnt locates source file.
URL url = getClass().getResource("utils/mount");
File file = new File(url.getPath());
this.copyEachFile(url.getPath(), "C:\\Users\\Nikhil\\Desktop\\" + mount); //this function takes in source path of file and copies it to destination path.
when I trace source path I get
/C:/Users/Nikhil/Documents/NetBeansProjects/Aroma-Installer/build/classes/aroma/installer/utils/mount
in netbeans and following in jar
/C:/Users/Nikhil/Documents/NetBeansProjects/Aroma-Installer/dist/Aroma-Installer.jar!/aroma/installer/utils/mount
When I run program in netbeans, file successfully copies but while running through jar, it says source doesnt exist.
Where is the problem?
Okay so I created a function and called it as follows.
this.copyFileFromJar("utils/mount", "C:\\Users\\Nikhil\\Desktop\\mount");
Definition of function is as follows.
public void copyFileFromJar(String source, String destination) throws IOException{
File dest = new File(destination);
if(!dest.exists()){
dest.createNewFile();
}
InputStream in = null;
OutputStream out = null;
try{
in = this.getClass().getResourceAsStream(source); //Important step, it returns InputStream which can be manipulated as per need.
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
JOptionPane.showMessageDialog(null, "File Successfully copied at" + dest.getAbsolutePath());
System.out.println("File Writing......" + dest.getName());
}
finally{
in.close();
out.close();
}
}
And now I am able to copy files from jar file to user specified location.
Hope this helps anybody who is looking for same kind of problem.

Downloading bulk files from sharepoint library

I want to download the files from a sharepoint document library through code as there are thousand of files in the document library.
I am thinking of creating console application, which I will run on sharepoint server and download files. Is this approach correct or, there is some other efficient way to do this.
Any help with code will be highly appreciated.
Like SigarDave said, it's perfectly possible to achieve this without writing a single line of code. But if you really want to code the solution for this, it's something like:
static void Main(string[] args)
{
// Change to the URL of your site
using (var site = new SPSite("http://MySite"))
using (var web = site.OpenWeb())
{
var list = web.Lists["MyDocumentLibrary"]; // Get the library
foreach (SPListItem item in list.Items)
{
if (item.File != null)
{
// Concat strings to get the absolute URL
// to pass to an WebClient object.
var fileUrl = string.Format("{0}/{1}", site.Url, item.File.Url);
var result = DownloadFile(fileUrl, "C:\\FilesFromMyLibrary\\", item.File.Name);
Console.WriteLine(result ? "Downloaded \"{0}\"" : "Error on \"{0}\"", item.File.Name);
}
}
}
Console.ReadKey();
}
private static bool DownloadFile(string url, string dest, string fileName)
{
var client = new WebClient();
// Change the credentials to the user that has the necessary permissions on the
// library
client.Credentials = new NetworkCredential("Username", "Password", "Domain");
var bytes = client.DownloadData(url);
try
{
using (var file = File.Create(dest + fileName))
{
file.Write(bytes, 0, bytes.Length); // Write file to disk
return true;
}
}
catch (Exception)
{
return false;
}
}
another way without using any scripts is by opening the document library using IE then in the ribbon you can click on Open in File Explorer where you can then drag and drop the files right on your desktop!

Resources