Convert Password Protected Zip file to Enc File using c# - c#

I have used the following below code to convert the zip file to enc file but its not working perfectly, please help me to solve this issue
Also if there is any third party tool to convert the zip to enc file please mention the details about it .
Thanks in Advance
try
{
string startPath = "";
string path = #"F:\Augustin\UpTest\Upload\";
DirectoryInfo objdirinfovikramfile = new DirectoryInfo(path);
if (objdirinfovikramfile.Exists)
{
errorcheck = "a";
foreach (DirectoryInfo objdirenmvikramfile in objdirinfovikramfile.GetDirectories())
{
string checkvikramfile = "";
checkvikramfile = objdirenmvikramfile.Name;
startPath = path + checkvikramfile + "\\";
string zipPath = path + checkvikramfile + ".zip";
string sub = zipPath.Split('\\').Last();
Boolean decrypt = false;
FileManager obj = new FileManager();
Int64 secure_count = 0;
while (secure_count <= 3 && !decrypt)
{
decrypt = obj_viki1.Decryption(zipPath, zipPath.Replace(".zip", ".enc"), "dietcoke1"); //DLL Function
secure_count++;
}
if (secure_count > 3 && !decrypt)
{
File.Copy(zipPath, path + "\\FAILED\\" + zipPath.Split('\\').Last(),true );
File.Copy(zipPath, path + "\\FAILED\\" + zipPath.Split('\\').Last(), true);
}
else
{
File.Copy(zipPath, path + "\\SUCCESS\\" + zipPath.Split('\\').Last(), true);
}
}
}
}
catch (Exception ex)
{
Error_log("FileProcess Enc: " + errorcheck + " ", ex.ToString());
Application.Exit();
}

Related

Copy file code?

I need a copy file on folder to another folder and i'm use this
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string file in files)
{
folderBrowserDialog1.ShowDialog();
string xx = folderBrowserDialog1.SelectedPath;
folderBrowserDialog1.ShowDialog();
string yy = folderBrowserDialog1.SelectedPath;
File.Copy(xx, yy);
But is not working.
Why?
Try this code.
I assume you want to read a file then write it to new one.
Hope it helps.
string sourceFile;
string newFile = "C:\NewFile\NewFile.txt";
string fileToRead = "C:\ReadFile\ReadFile.txt";
bool overwriteExistingFile = true; //change to false if you want no to overwrite the existing file.
bool isReadSuccess = getDataFromFile(fileToRead, ref sourceFile);
if (isReadSuccess)
{
File.Copy(sourceFile, newFile, overwriteExistingFile);
}
else
{
Console.WriteLine("An error occured :" + sourceFile);
}
//Reader Method you can use this or modify it depending on your needs.
public static bool getDataFromFile(string FileToRead, ref string readMessage)
{
try
{
readMessage = "";
if (!File.Exists(FileToRead))
{
readMessage = "File not found: " + FileToRead;
return false;
}
using (StreamReader r = new StreamReader(FileToRead))
{
readMessage = r.ReadToEnd();
}
return true;
}
catch (Exception ex)
{
readMessage = ex.Message;
return false;
}
}
It seems that you do not use filenames in your source code.
I made an example. File copy function.
public void SaveStockInfoToAnotherFile(string sPath, string dPath, string filename)
{
string sourcePath = sPath;
string destinationPath = dPath;
string sourceFile = System.IO.Path.Combine(sourcePath, filename);
string destinationFile = System.IO.Path.Combine(destinationPath, filename);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
//folderBrowserDialog1.ShowDialog();
//string xx = folderBrowserDialog1.SelectedPath;
//string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
//folderBrowserDialog1.ShowDialog();
//string yy = folderBrowserDialog1.SelectedPath;
//foreach (string file in files)
//{
// File.Copy(xx + "\\" + Path.GetFileName(file), yy + "\\" + Path.GetFileName(file));

Automatically create folders if does not exists in C#

So, I am trying to create a file at a specific path but the code I have doesn't allows me to create folders.
This is the code I have:
public void LogFiles()
{
string data = string.Format("LogCarga-{0:yyyy-MM-dd_hh-mm-ss}.txt", DateTime.Now);
for (int linhas = 0; linhas < dataGridView1.Rows.Count; linhas++)
{
if (dataGridView1.Rows[linhas].Cells[8].Value.ToString().Trim() != "M")
{
var pathWithEnv = #"%USERPROFILE%\AppData\Local\Cargas - Amostras\_logs\";
var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (StreamWriter writer = File.AppendText(filePath + data))
{
string carga = dataGridView1.Rows[linhas].Cells[0].Value.ToString();
string referencia = dataGridView1.Rows[linhas].Cells[1].Value.ToString();
string quantidade = dataGridView1.Rows[linhas].Cells[2].Value.ToString();
string dataemissao = dataGridView1.Rows[linhas].Cells[3].Value.ToString();
string linha = dataGridView1.Rows[linhas].Cells[4].Value.ToString();
string marca = dataGridView1.Rows[linhas].Cells[5].Value.ToString().Trim();
string descricaoweb = dataGridView1.Rows[linhas].Cells[6].Value.ToString().Trim();
string codprod = dataGridView1.Rows[linhas].Cells[7].Value.ToString().Trim();
string tipoemb = dataGridView1.Rows[linhas].Cells[8].Value.ToString().Trim();
string nomepc = System.Environment.MachineName;
writer.WriteLine(carga + ", " + referencia + ", " + quantidade + ", " + dataemissao + ", " + linha + ", " + marca + ", " + descricaoweb + ", " + codprod + ", "
+ tipoemb + ", " + nomepc);
}
}
}
}
}
This %USERPROFILE%\AppData\Local\ in the universal path and I want to automatically create the \Cargas - Amostras\_logs\.
Do you have any idea how to do it?
The simpelest solution is replace
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
with
System.IO.Directory.CreateDirectory(filePath)
That will create the directory if it does not exist or do nothing if it does.
You need to create two checks, for your first folder and then second directory.
var pathWithEnv = #"%USERPROFILE%\AppData\Local\Cargas - Amostras\";
if (System.IO.Directory.Exists(pathWithEnv))
{
pathWithEnv = System.IO.Path.Combine(pathWithEnv, #"_logs\");
if (System.IO.Directory.Exists(pathWithEnv))
{
//Do what you want to do, both directories are found.
}
else
{
System.IO.Directory.CreateDirectory(pathWithEnv);
//Do what you want to do, both directories are available.
}
}
else
{
System.IO.Directory.CreateDirectory(pathWithEnv);
pathWithEnv = System.IO.Path.Combine(pathWithEnv, #"_logs\");
if (System.IO.Directory.Exists(pathWithEnv))
{
//Do what you want to do, both directories are available now.
}
else
{
System.IO.Directory.CreateDirectory(pathWithEnv);
//Do what you want to do, both directories are created.
}
}

How to close a file handle byte[] firstHash = MD5.Create().ComputeHash(f1.OpenRead());

I have a piece of code which works nicely. However I need to close the file so I can perform file.move() function, this doesn't work because the file is used by another process. I need to use the correct file handle - can you guide me in the right direction?
static void DSCheckForDuplicates(string incomingfolder, string incomingarchivefolder, string quarantinefolder)
{
string[] F1 = Directory.GetFiles(incomingfolder);
string fname = "";
long FileOne;
long FileTwo;
bool FilesAreTrullyIdentical;
string FileStatusValue = "";
string Result = "";
string NewLocation = "";
foreach (string fileName in F1)
{
// FILE EXCLUSION LIST FROM DUPLICATE FILE CHECKS
if (fileName.Contains("xxx.DAT") || fileName.Contains("xxx.txt") || fileName.Contains("OrderHead.txt") )
{
Console.WriteLine("\nKnown file type..");
}
else
{
fname = Path.GetFileName(fileName);
FilesAreTrullyIdentical = false;
Console.WriteLine("Files present : The file is {0}...Press any key\n", fileName);
//Console.ReadKey();
if (File.Exists(incomingarchivefolder + #"\" + fname))
{
DuplicateFlag = true;
FileStatusValue = "DuplicateFilename";
DuplicateFileCounter++;
Narative += string.Format("\n________________________________________________________________________________________________________________\nFile Exception :{0}\n####################\n", DuplicateFileCounter );
Narative += string.Format ("Same filename exists in the two compared directories, Checking potential duplicate file contents in :{0}................\n", fileName);
FileInfo f1 = new FileInfo(fileName);
FileOne = f1.Length;
FileInfo f2 = new FileInfo(incomingarchivefolder + #"\" + fname);
FileTwo = f2.Length;
//if (FileOne == FileTwo)
//{
byte[] firstHash = MD5.Create().ComputeHash(f1.OpenRead());
byte[] secondHash = MD5.Create().ComputeHash(f2.OpenRead());
for (int i = 0; i < firstHash.Length; i++)
{
FilesAreTrullyIdentical = true;
if (firstHash[i] != secondHash[i])
FilesAreTrullyIdentical = false;
}
if (FilesAreTrullyIdentical == true)
{
FileStatusValue = "DuplicationFileNameDuplicateContents";
Console.WriteLine("Processed : WARNING!!! identical FILES contents FOUND {0}\n and {1}\n..............\n", fileName, incomingarchivefolder + #"\" + fname);
Narative += string.Format("\tProcessed : Please delete from incoming, WARNING!!! identical FILES contents\n\nPLEASE DELETE FILE:\t{0}..............\n", fileName);
Result = Path.GetFileName(fileName);
NewLocation += quarantinefolder + "\\" + Result;
Console.WriteLine("\n\n {0} ->\nMoving to {1} , press any key", fileName, NewLocation);
Console.ReadKey();
//File.Move(fileName, NewLocation); // THIS DOESNT WORK
You could capture the stream from f1.OpenRead() into a variable & pass that calling Close() when your done, instead however you should put the stream and MD5 reference within a using construct as currently you leave them undisposed. (This will also close the stream for you)
byte[] firstHash;
using (var stream = f1.OpenRead())
using (var md5 = MD5.Create())
{
firstHash = md5.ComputeHash(stream);
}

C# fail to create file in directory if has other file

Can someone help me, I just learning C# for about 2 month, I have this problem,
i'm building a class for filter data from temp file and create the result in new txt file inside directory, if directory is empty nor at the same date, it build perfectly, and if there another file at same date it should create with increase the last number at lastname.
My problem when I run code, it is not creating if the directory has files with the same dates, then the result should be something like this:
C:\result_2014051301.txt
C:\result_2014051401.txt
C:\result_2014051402.txt <-- Failed, it is not ..2014051401.txt
class Entity2
{
public Entity2()
{
string fileTemp = "DEFAULT.temp";
string indexD = Properties.Settings.Default.ChIndex2D;
string indexC = Properties.Settings.Default.ChIndex2C;
string indexS = Properties.Settings.Default.ChIndex2S;
string tempPath = AppDomain.CurrentDomain.BaseDirectory;
string targetPath = Properties.Settings.Default.ExtractALL_DIR;
string SourceFile = Path.Combine(tempPath, fileTemp);
string tempFileX = Path.GetTempFileName();
if (!System.IO.Directory.Exists(targetPath))
{
System.Windows.Forms.MessageBox.Show("Error missing .temp", "Message Box");
}
else
{
string ext = ".txt";
int sequence = 0;
DateTime dateFileName = DateTime.Today;
string discode = Properties.Settings.Default.ChannelID_2;
string filename = discode + "_" + dateFileName.ToString("yyyyMMdd");
string pathX = Properties.Settings.Default.ExtractALL_DIR + #"/Channel2";
if (!Directory.Exists(pathX))
{
Directory.CreateDirectory(pathX);
}
string[] files = Directory.GetFiles(pathX, filename + "*.txt", SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
Array.Sort(files);
string lastFilename = files[files.Length - 1];
sequence = Int32.Parse(lastFilename.Substring(0, lastFilename.Length - 4).Replace(pathX + filename, ""));
}
sequence++;
string newFileName = filename + sequence.ToString().PadLeft(2, '0') + ext;
string DestFile = Path.Combine(pathX, newFileName);
using (var ab = new StreamReader(SourceFile))
using (var cd = new StreamWriter(DestFile))
{
string lineX;
while ((lineX = ab.ReadLine()) != null)
{
if (lineX.LastIndexOf("100", 3) != -1 || lineX.LastIndexOf("MGR", 15) != -1 || lineX.LastIndexOf(indexC, 15) != -1)
{
lineX = lineX.Replace(indexD, "");
lineX = lineX.Replace("DEFAULT", discode);
if (lineX.LastIndexOf("800", 3) != -1)
{
lineX = lineX.Replace(indexS, "");
}
cd.WriteLine(lineX);
}
}
}
}
}
}
This piece is not functioning correctly:
Int32.Parse(lastFilename.Substring(0, lastFilename.Length - 4).Replace(pathX + filename, ""));
pathX + filename is C:\folderfile.txt not C:\folder\file.txt.
You either need to add the \ or call Path.Join.
That will cause the Parse operation to fail since it tries to consume the who string (minus the extension).

Error: "The process cannot access.... because it is being used by another process. " in Delete Image

I know others had a similar problem but my problem is specific for image...
I have an image function like below:
static public string Setimage(PictureBox pictureBox, OpenFileDialog ofd,string nameform,string folderform)
{
ofd.Title = "Select Pictures";
ofd.Filter = "Pictures(*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png | All file (*.*)| *.*";
ofd.DefaultExt = ".jpg"; // Default file extension
string namefile = "";
// Process open file dialog box results
if (ofd.ShowDialog() == DialogResult.OK)
{
// try
//{
string fileName = ofd.FileName;
if (ofd.SafeFileName.Length <= 50)
if (Image.FromFile(fileName).Width >= 640 && Image.FromFile(fileName).Height >= 480)
{
namefile = ofd.SafeFileName;
if (namefile != "Null_0_Null" || namefile != null)
{
string oldPath = #ofd.FileName;
string newFileName = namefile;
newpath = Application.StartupPath + #"\userpictures\" + #"Apartment\";
deladdress = newpath + folderform + #"\" + #newFileName;
Random rand = new Random();
string pp=newpath+folderform;
// string pdest;
#region Check Directory And File To copy
if (Directory.Exists(newpath + folderform))
{
if (!File.Exists(newpath + folderform + #"\" + #newFileName))
File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
// else
// {
// File.Delete(newpath + folderform + #"\" + #newFileName);
// File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
//}
}
else
{
Directory.CreateDirectory(newpath + folderform);
File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
}
#endregion
pictureBox.BackgroundImage = Image.FromFile(newpath + folderform + #"\" + #newFileName);
}
else { MessageBox.Show("filename" + namefile + "Not valid"); }
}
else { MessageBox.Show("Size of file not valid"); }
else { MessageBox.Show("size of name file not valid"); }
// }
// catch { MessageBox.Show("your file that you selected is not valid please select anyone."); }
}
return namefile;
}
For loading image I have this function:
static public void loadimage(PictureBox pictureBox, string img, string nameform, string folderform)
{
try
{
if (img != "Null_0_Null")
if (!System.IO.File.Exists(Application.StartupPath + #"\userpictures\" + nameform + #"\" + folderform + #"\" + img))
{
pictureBox.BackgroundImage = Image.FromFile(Application.StartupPath + "\\filepictures\\default4.PNG");
}
else
{
pictureBox.BackgroundImage =Image.FromFile(Application.StartupPath + #"\userpictures\" + nameform + #"\" + folderform + #"\" + img);
}
}
catch { }
}
In my form I call this functions. For set image I write a private string in my form:
string img1;
And for loading image in my form load write this:
loadimage(pictureBox1, "Blue hills.jpg","me", "Apartment");
img1 = "Blue hills.jpg";
For Setimage I have this:
img1=Setimage(pictureBox1, openFileDialog1,"me", "Apartment");
And when I use this code for delete image show me error "process can not be access ..."
System.IO.File.Delete("image path");
When you use Image.FromFile, that will open a file handle to that file and keep it open until the image is disposed.
You should:
Only call Image.FromFile once and reuse the object in Setimage (you're loading it twice in a single if condition...)
Dispose of every Image when you're done with it
Dispose of the old BackgroundImage before you set the new one
So long as you dispose of every Image which is related to the file before you delete the file, you should be okay.

Categories