I'm trying to set a password for a zip file using SharpZipLib library with .Net Core.
I have followed this example in order to set a password, however once the zip file has been created, the files are in there and the zip file is create, however there is no password.
// Create a password for the Zipfolder
// https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples
using (ICSharpCode.SharpZipLib.Zip.ZipFile ZipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(Path.GetFileName(destinationPath)))
{
ZipFile.Password = "foo";
ZipFile.Add(destinationPath, "");
}
None of the above answers worked for me,With that being said I found this Fast Zip class within the SharpZipLib library that has worked for me.
// Create a password for the Zipfolder
// https://github.com/icsharpcode/SharpZipLib/wiki
ICSharpCode.SharpZipLib.Zip.FastZip zipFile = new ICSharpCode.SharpZipLib.Zip.FastZip();
zipFile.Password = "foo";
zipFile.CreateEmptyDirectories = true;
zipFile.CreateZip(destinationPath,tempPath, true, "");
The only thing I don't like about it however is that is doesn't implement IDisposable
I used the Example from the wiki and it worked without a Problem.
Code:
using (FileStream fsOut = File.Create(#"d:\temp\sharplib_pwtest.zip"))
using (ZipOutputStream zipStream = new ZipOutputStream(fsOut)) {
zipStream.SetLevel(3);
zipStream.Password = "Testpassword";
var folderName = #"D:\temp\sharpZipLibTest\";
int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1);
CompressFolder(folderName, zipStream, folderOffset);
}
You just need to put BeginUpdate() and CommitUpdate() and that will reflect in your output.
using (ICSharpCode.SharpZipLib.Zip.ZipFile ZipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(Path.GetFileName(destinationPath)))
{
ZipFile.BeginUpdate();
ZipFile.Password = "foo";
ZipFile.Add(destinationPath, "");
ZipFile.CommitUpdate();
}
Thanks for y'all help. I took #traveler3668 answer and added a little bit more details. I used paths from my project as an example.
This worked for me:
using System.Web.Security; //to generate password
using ICSharpCode.SharpZipLib.Zip;
string password = Membership.GeneratePassword(32, 10);
var zip = new FastZip();
zip.Password = password;
zip.CreateZip(
"C:\\dev\\InterfaceStatus\\InterfaceStatus\\App_Data\\test-folder_31-10-2022_11-23-54.zip",
"C:\\dev\\InterfaceStatus\\InterfaceStatus\\App_Data\\test-folder_31-10-2022_11-23-54",
true,
""
);
Related
I'm trying to download a file using HTTP, and here is the code.
With this, I have a directory made with a correct name, and a file within the directory made with a correct name, but there is NOTHING WRITTEN in the file.
PostMethod post = new PostMethod(serverUrl);
post.setRequestEntity(entity);
httpclient.executeMethod(post);
File contentDirectory = new File(fileFullPath);
if(contentDirectory.exists() == false){
contentDirectory.mkdir();
}
File localFile = new File(fileFullPath + File.separator + filename);
int readBuf = 0;
byte[] buf = new byte[Utils.getBufferSize()]; (BufferSize Checked)
InputStream is = null;
is = post.getResponseBodyAsStream();
FileOutputStream fos = new FileOutputStream(localFile);
while((readBuf = is.read(buf))!= -1){
fos.write(buf, 0, readBuf);
logger.info("readBuf : "+readBuf);
}
is.close();
fos.close();enter code here
if(localFile.exists()) Transfer_Success = true;
Being a noob I am, turns out all this time I was sending post method to a wrong servlet. A mistake only novices make.
So I have the bytes transferred correctly, but this time the image files can't be open due to wrong encoding type or something. I'm on to resolving this.
I am using the below code to upload image file Amazon AWS S3 server..
using (var msImage = new MemoryStream(arrayImage))
using (var msImageL1 = new MemoryStream())
using (var bmImage = (Bitmap)Image.FromStream(msImage))
using (var bmPicture01 = new Bitmap(924, 693))
using (Graphics gPicture01 = Graphics.FromImage(bmPicture01))
{
using (IAmazonS3 s3client = new AmazonS3Client(accessKey, secretKey, RegionEndpoint.APSoutheast1))
{
PutObjectRequest putObjectRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = "sample/5.jpg",
InputStream = msImage
};
s3client.PutObject(putObjectRequest);
}
gPicture01.InterpolationMode = InterpolationMode.HighQualityBicubic;
gPicture01.DrawImage(bmImage, 0, 0, 924, 693);
bmPicture01.Save(msImageL1, ImageFormat.Jpeg);
using (IAmazonS3 s3client = new AmazonS3Client(accessKey, secretKey, RegionEndpoint.APSoutheast1))
{
PutObjectRequest putObjectRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = "sample/6.jpg",
InputStream = msImageL1
};
s3client.PutObject(putObjectRequest);
}
}
The first code, which is uploading "5.jpg" is working fine, and uploading successfully. But the other code is now working and giving exception that,
Message=The request was aborted: The request was canceled.
Message=Cannot close stream until all bytes are written.
I am using Amazon Web Services SDK for .NET version 2.0.2.3
Please suggest what might be going wrong here..
Since there hasn't been any other answer and my first response got deleted because it "does not really answer the question", I'm going to try and rephrase it.
You said:
Please suggest what might be going wrong here..
My suggestion is that there is nothing wrong with you code. Instead it's a possible bug with version 2.0.1 and later. See https://forums.aws.amazon.com/thread.jspa?threadID=139612&tstart=0 (requires log in). I've tried with version 2.0.2.3 and the bug is still there.
You can test this by using a previous version.
The issue here is that bmPicture01.Save(msImageL1, ImageFormat.Jpeg); saves the bitmap to a string but doesn't reset the position of the stream to 0. You will need to do that before passing the stream to PutObject.
I am looking to remotely fire a delete command using the MSDeploy API through c# code.
I want to achieve the following command:
msdeploy.exe -verb:delete -dest:contentPath="/folderName/filename.txt"
instead of through running an unmanaged external executable, I want to execute this using the MSDeploy .Net API.
Assuming you're trying to delete an absolute filepath (rather than a file in a website), you're looking for something like this:
DeploymentObject destObject = DeploymentManager.CreateObject(
DeploymentWellKnownProvider.FilePath, "/foldername/filename.txt");
DeploymentObject sourceObject = DeploymentManager.CreateObject("auto", "");
DeploymentBaseOptions baseOptions = new DeploymentBaseOptions();
DeploymentSyncOptions syncOptions = new DeploymentSyncOptions
{
DeleteDestination = true;
};
DeploymentChangeSummary results = sourceObject.SyncTo(
destObject, baseOptions, syncOptions);
// results.ObjectsDeleted == 1
I've found the answer thanks to Richard Szalay's leading and i've used the ContentPath provider as this is a common provider used by VS Publishing so the chances of having permissions is high:
var deployBaseOptions = new DeploymentBaseOptions
{
ComputerName = "https://mywebserver.com:8172/msdeploy.axd?sitename=yourIISWebsiteName",
UserName = "username",
Password = "password",
UseDelegation = true,
AuthenticationType = "Basic"
};
var syncOptions = new DeploymentSyncOptions
{
DeleteDestination = true
};
var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath,
"yourIISWebsiteName" + "/fileToDelete.txt",
destBaseOptions);
var results = deploymentObject.SyncTo(deployBaseOptions, syncOptions);
The weird thing is that results always shows 3 files deleted even when there is only one...?!
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.
I am developing my down blog engine based on file system storage, very much interested to use Markdown for keeping file and storage compressed. I am able to figure out the way when user submit the content using Markdown editor (that's I am using now while writing the code!!) but also would like to enhance the feature by allowing Window Live Writer and Metablog API thus it is very important for me to transform vice versa (HTML -> Markup).
I am not able to find any example or specific code snippet that can help me. Advise would be much appreciated.
Reference:
http://code.google.com/p/markdownsharp/
I am using above repository.
Cheer!
Nilay.
You can use Pandoc with a wrapper as shown in the answer to this question:
Convert Html or RTF to Markdown or Wiki Compatible syntax?
Edit:
Here's a slightly modified (to dispose of process resources) version of the function that #Rob wrote:
private string Convert(string source) {
string processName = #"C:\Program Files (x86)\Pandoc\bin\pandoc.exe";
string args = "-r html -t markdown";
ProcessStartInfo psi = new ProcessStartInfo(processName, args) {
RedirectStandardOutput = true,
RedirectStandardInput = true,
CreateNoWindow = true,
UseShellExecute = false
};
var outputString = "";
using (var p = new Process()) {
p.StartInfo = psi;
p.Start();
byte[] inputBuffer = ASCIIEncoding.UTF8.GetBytes(source);
p.StandardInput.BaseStream.Write(inputBuffer, 0, inputBuffer.Length);
p.StandardInput.Close();
using (var sr = new StreamReader(p.StandardOutput.BaseStream)) {
outputString = sr.ReadToEnd();
}
}
return outputString;
}
I'm not sure how practical this is but it works.