Scenario: upload file than try zip it using DotNetZip with password protection, password is generated with Membership.GeneratePassword() method. Everything is working fine except that sometimes user is not able to unzip files with generated password. Wired thing is that this happens only sometimes let's say 1 out of 15 times.
Generate password:
public static String FilePassword()
{
while (_filePassword.Length < 12)
{
_filePassword += string.Concat(Membership.GeneratePassword(1, 0).Where(char.IsLetterOrDigit));
}
return _filePassword;
}
Save file:
if (FileUploadControl.HasFile)
{
fileName = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(FileSavePath + fileName);
// Archive uploaded file to zip.
using (ZipFile zip = new ZipFile())
{
// File to be archived.
var file = FileUploadControl.PostedFile;
// Enable encryption of file
zip.Encryption = EncryptionAlgorithm.PkzipWeak;
// Set password.
zip.Password = Settings.FilePassword();
// Set temporary folder path for archive process.
zip.TempFileFolder = tempPath;
// Add file to archive with its path.
zip.AddFile(FileSavePath + file.FileName, "");
File objFile = new File(file.FileName, FileSavePath);
// Save zip file with the name as file ID.
zip.Save(FileSavePath + file.FileName);
}
}
I logged password while creating in method and also while protecting zip file with password, they are always matching, I cannot see what's wrong, why sometimes while unzipping file it shows wrong password.
Why do you use the static global variable _filePassword in FilePassword() instead of one in scope?
This way it could be modified from outside, or possible even still contain the last used value. Also it isn't thread safe without lock.
Settle with a local variable and it should be fine.
public static String FilePassword()
{
string retString = string.Empty;
while (retString.Length < 12)
{
retString += string.Concat(Membership.GeneratePassword(1, 0).Where(char.IsLetterOrDigit));
}
return retString;
}
You can log a return Value too.
Sample for understanding
if (FileUploadControl.HasFile)
{
fileName = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(FileSavePath + fileName);
string filePassword = Settings.FilePassword(); // Contains the Password
using (ZipFile zip = new ZipFile())
{
var file = FileUploadControl.PostedFile;
zip.Encryption = EncryptionAlgorithm.PkzipWeak;
zip.Password = filePassword; // <-- Set password for ZIP
zip.TempFileFolder = tempPath;
zip.AddFile(FileSavePath + file.FileName, "");
File objFile = new File(file.FileName, FileSavePath);
zip.Save(FileSavePath + file.FileName);
}
// Log this value!
Log(filePassword);
}
Related
I have developed this C# System that authentically encrypts files using AES-GCM algorithm. However, I don't want the encrypted file to be in same folder as original folder. How can I change it? Below is the sniplet of my code and where exactly I need help.
foreach (string inputFilePath in inputFilePaths)
{
// Proceed if file exists
if (File.Exists(inputFilePath))
{
try
{
// Encrypt
byte[] key = PasswordAsKey();
string[] encryptedFileContents = AesGcmFileEncryption.Encrypt(inputFilePath, key);
// Here is where I need clarification
string outputFilePath = inputFilePath;
outputFilePath += ".AEncrypt";
if (File.Exists(outputFilePath))
{
skippedBecauseFileExists = true;
}
else
{
File.WriteAllLines(outputFilePath, encryptedFileContents);
counter++;
// Status
label10.Text = "Copied and encrypted \"" + Path.GetFileName(inputFilePath) + "\"";
}
}
catch (Exception ex)
You can create subdirectory and write the encrypted files there.
string inputDir = Path.GetDirectoryName(inputFilePath);
string outputDir = Path.Combine(inputDir, "EncryptedFiles");
Directory.CreateDirectory(outputDir);
string outputFileName = Path.GetFileName(inputFilePath) + ".AEncrypt";
string outputFilePath = Path.Combine(outputDir, outputFileName);
Here I extract directory name from inputFilePath and append "EncryptedFiles" to it. Then I create your new file name and append it to the generated directory.
Directory.CreateDirectory() will create directory if it doesn't exist.
Currently i am taking in multiple .txt files from a directory i have specified (sourceDirectory). I am generating new .csv files with the same name as the .txt files - one .csv file for each .txt file.
However i want to generate these new files in another directory which i have specified (directoryPath). If i run my program once it creates these files in the initial directory, however if i run my program again it now generates the files in the destination directory.
The following is my code where i complete the above:
static void Main(string[] args)
{
string sourceDirectory = #"C:directoryWhereTXTFilesAre";
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt", SearchOption.AllDirectories);
foreach (string currentFile in txtFiles)
{
readFile(currentFile);
}
string directoryPath = #"C:\destinationForCSVFiles";
}
I then create the new .csv files name based on the original .txt file like this:
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
// build hash set of filenames for performance
var files = new HashSet<string> (Directory.GetFiles(folder));
for (var index = 0; index < maxAttempts; index++)
{
// first try with the original filename, else try incrementally adding an index
var name = (index == 0)
? fileName
: String.Format("{0} ({1}){2}", fileBase, index, ext);
// check if exists
var fullPath = Path.Combine(folder, name);
string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
if (files.Contains(CSVfileName))
continue;
// try to create the file
try
{
return new FileStream(CSVfileName, FileMode.CreateNew, FileAccess.Write);
}
catch (DirectoryNotFoundException) { throw; }
catch (DriveNotFoundException) { throw; }
catch (IOException)
{
}
}
I don't see why it's creating the .csv files initially in the same directory that the .txt files are in and then second time i run my code it creates them in the directoryPath.
Desired output: sourceDirectory left as it is with only .txt files and directoryPath to hold the .csv files.
The only other place i call CreateFileWithUniqueName is within my readFile method, the code is below:
using (var stream = CreateFileWithUniqueName(#"C:destinationFilePath", currentFile))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedFileName = newFileName;
}
It seems that you are passing the full filename of the source file. This confuses the Path.Combine inside the CreateFileWithUniqueFilename because you are falling in this subtle remarks found on the documentation of Path.Combine
paths should be an array of the parts of the path to combine. If the
one of the subsequent paths is an absolute path, then the combine
operation resets starting with that absolute path, discarding all
previous combined paths.
You can fix it easily with
using (var stream = CreateFileWithUniqueName(#"C:\destinationFilePath",
Path.GetFileName(currentFile)))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
newFileName = stream.Name;
Globals.CleanedFileName = newFileName;
}
Or better extract the filename without path inside the CreateFileWithUniqueName
static FileStream CreateFileWithUniqueName(string folder, string fileName, int maxAttempts = 1024)
{
var fileBase = Path.GetFileName(fileName);
fileBase = Path.GetFileNameWithoutExtension(fileBase);
var ext = Path.GetExtension(fileBase);
also, you should build your CSVfileName using the cleaned filename
var name = (index == 0)
? String.Format("{0}{1}", fileBase, ext);
: String.Format("{0} ({1}){2}", fileBase, index, ext);
var fullPath = Path.Combine(folder, name);
string CSVfileName = Path.ChangeExtension(fullPath, ".csv");
if (files.Contains(CSVfileName))
continue;
I already protect the csv files with zip by using the ionic.zip.dll
see the below code
using (ZipFile zip = new ZipFile())
{
TargetFileName = TargetNamePrefix;
OutPutDirectoryPath = TargetLocation + "\\" + TargetNamePrefix + ".zip";
zip.Password = zipFilePassword;
zip.AddFiles(FilePaths, TargetNamePrefix);
zip.Save(OutPutDirectoryPath)
}
here file paths is string[] variable it consists of files(csv/text) Names.
TargetNamePrefix means inside zipfile folder Name.OutPutDirectoryPath means
output directoty with zipfileName.
then How can i Open the those protected files in write mode why because I want to write Datainto the Protected csv file.
You can just extract them using a similar method:
using(ZipFile zip = ZipFile.Read(OutPutDirectoryPath))
{
zip.Password = zipFilePassword;
try
{
zip.ExtractAll(TargetLocation);
}
catch (BadPasswordException e)
{
// handle error
}
}
Update
Access single file entry into a stream without extracting
string entry_name = TargetNamePrefix + ".csv"; // update this if needed
using (ZipFile zip = ZipFile.Read(OutPutDirectoryPath))
{
// Set password for file
zip.Password = zipFilePassword;
// Extract entry into a memory stream
ZipEntry e = zip[entry_name];
using(MemoryStream m = new MemoryStream())
{
e.Extract(m);
// Update m stream
}
// Remove old entry
zip.RemoveEntry(entry_name);
// Add new entry
zip.AddEntry(entry_name, m);
// Save
zip.Save(OutPutDirectoryPath);
}
string host = #"ftphost";
string username = "user";
string password = "********";
string localFileName = System.IO.Path.GetFileName(#"localfilename");
string remoteDirectory = "/export/";
using (var sftp = new SftpClient(host, username, password))
{
sftp.Connect();
var files = sftp.ListDirectory(remoteDirectory);
foreach (var file in files)
{
if (!file.Name.StartsWith("."))
{
string remoteFileName = file.Name;
if (file.LastWriteTime.Date == DateTime.Today)
Console.WriteLine(file.FullName);
File.OpenWrite(localFileName);
string sDir = #"localpath";
Stream file1 = File.OpenRead(remoteDirectory + file.Name);
sftp.DownloadFile(remoteDirectory, file1);
}
}
}
I am using SSH.NET (Renci.SshNet) library to work with an SFTP server. What I need to do is grab files from a specific folder on the SFTP server based on today's date. Then copy those files from the SFTP server to a local drive a server of mine.
Above is the code I have but it is not working. Sometimes it says file does not exist but sometimes the files I will be downloading will not be on my local servers but I need to download whatever files were uploaded to the remote folder for that day.
Can someone take a look and see what is wrong? I believe it has something to do with the stream portion. I have worked with FTP much besides uploading files which I took some previous code I had and thought I could reverse the process but that isn't working. The code I used is based off of this example.
A simple working code to download a file with SSH.NET library is:
using (Stream fileStream = File.Create(#"C:\target\local\path\file.zip"))
{
sftp.DownloadFile("/source/remote/path/file.zip", fileStream);
}
See also Downloading a directory using SSH.NET SFTP in C#.
To explain, why your code does not work:
The second parameter of SftpClient.DownloadFile is a stream to write a downloaded contents to.
You are passing in a read stream instead of a write stream. And moreover the path you are opening read stream with is a remote path, what cannot work with File class operating on local files only.
Just discard the File.OpenRead line and use a result of previous File.OpenWrite call instead (that you are not using at all now):
Stream file1 = File.OpenWrite(localFileName);
sftp.DownloadFile(file.FullName, file1);
Or even better, use File.Create to discard any previous contents that the local file may have.
I'm not sure if your localFileName is supposed to hold full path, or just file name. So you may need to add a path too, if necessary (combine localFileName with sDir?)
While the example works, its not the correct way to handle the streams...
You need to ensure the closing of the files/streams with the using clause..
Also, add try/catch to handle IO errors...
public void DownloadAll()
{
string host = #"sftp.domain.com";
string username = "myusername";
string password = "mypassword";
string remoteDirectory = "/RemotePath/";
string localDirectory = #"C:\LocalDriveFolder\Downloaded\";
using (var sftp = new SftpClient(host, username, password))
{
sftp.Connect();
var files = sftp.ListDirectory(remoteDirectory);
foreach (var file in files)
{
string remoteFileName = file.Name;
if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today))
using (Stream file1 = File.Create(localDirectory + remoteFileName))
{
sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
}
}
}
}
My version of #Merak Marey's Code. I am checking if files exist already and different download directories for .txt and other files
static void DownloadAll()
{
string host = "xxx.xxx.xxx.xxx";
string username = "###";
string password = "123";string remoteDirectory = "/IN/";
string finalDir = "";
string localDirectory = #"C:\filesDN\";
string localDirectoryZip = #"C:\filesDN\ZIP\";
using (var sftp = new SftpClient(host, username, password))
{
Console.WriteLine("Connecting to " + host + " as " + username);
sftp.Connect();
Console.WriteLine("Connected!");
var files = sftp.ListDirectory(remoteDirectory);
foreach (var file in files)
{
string remoteFileName = file.Name;
if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today)))
{
if (!file.Name.Contains(".TXT"))
{
finalDir = localDirectoryZip;
}
else
{
finalDir = localDirectory;
}
if (File.Exists(finalDir + file.Name))
{
Console.WriteLine("File " + file.Name + " Exists");
}else{
Console.WriteLine("Downloading file: " + file.Name);
using (Stream file1 = File.OpenWrite(finalDir + remoteFileName))
{
sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
}
}
}
}
Console.ReadLine();
}
Massimiliano's solution has one problem which will lead to files not being completely downloaded. The FileStream must be closed. This is especially a problem for encrypted files. They won't completely decrypt intermittently without closing the stream.
var files = sftp.ListDirectory(remoteVendorDirectory).Where(f => !f.IsDirectory);
foreach (var file in files)
{
var filename = $"{LocalDirectory}/{file.Name}";
if (!File.Exists(filename))
{
Console.WriteLine("Downloading " + file.FullName);
using (var localFile = File.OpenWrite(filename))
sftp.DownloadFile(file.FullName, localFile);
}
}
This solves the problem on my end.
var files = sftp.ListDirectory(remoteVendorDirectory).Where(f => !f.IsDirectory);
foreach (var file in files)
{
var filename = $"{LocalDirectory}/{file.Name}";
if (!File.Exists(filename))
{
Console.WriteLine("Downloading " + file.FullName);
using (var localFile = File.OpenWrite(filename))
sftp.DownloadFile(file.FullName, localFile);
}
}
Without you providing any specific error message, it's hard to give specific suggestions.
However, I was using the same example and was getting a permissions exception on File.OpenWrite - using the localFileName variable, because using Path.GetFile was pointing to a location that obviously would not have permissions for opening a file > C:\ProgramFiles\IIS(Express)\filename.doc
I found that using System.IO.Path.GetFileName is not correct, use System.IO.Path.GetFullPath instead, point to your file starting with "C:\..."
Also open your solution in FileExplorer and grant permissions to asp.net for the file or any folders holding the file. I was able to download my file at that point.
I am trying to zip and encrypt a chosen file from the user. Everything works fine except that I am zipping the whole path, i.e not the file itself. Below is my code, any help on how I can zip and encrypt on the chosen file.
openFileDialog1.ShowDialog();
var fileName = string.Format(openFileDialog1.FileName);
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
using (ZipFile zip = new ZipFile())
{
zip.Password = "test1";
zip.Encryption = EncryptionAlgorithm.WinZipAes256;
zip.AddFile(fileName);
zip.Save(path + "\\test.ZIP");
MessageBox.Show("File Zipped!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
You must set the file name explicitly for the zip-archive:
zip.AddFile(fileName).FileName = System.IO.Path.GetFileName(fileName);
This is how you can zip up a file, and rename it within the archive . Upon extraction, a file will be created with the new name.
using (ZipFile zip1 = new ZipFile())
{
string newName= fileToZip + "-renamed";
zip1.AddFile(fileToZip).FileName = newName;
zip1.Save(archiveName);
}
Reference : C# Examples