decrypt pgp files from a folder and moving it - c# - c#

I am trying to decrypt .pgp files from a location and then moving those files to another location. I looked into this article and code accordingly. In my code I am developing an application which will check to a certain location after every 100 seconds and if there are files then it will decrypt and move. but I am getting this exception The process cannot access the file 'c:\file.pgp' because it is being used by another process.
Here is my code where I am calling that class which I copied from that article.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//Do the stuff you want to be done every hour;
string sourcePath = #"files location";
string archivePath = #"move original file after decrypting location";
string targetPath = #"decrypted file location";
string pubkeyPath = #"public key location\PGPPublicKey.txt";
string privkeyPath = #"private key location\PGPPrivateKey.txt";
string fileName = "";
string destFile = "";
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
PGPDecrypt test = new PGPDecrypt(s,
privkeyPath,
"password",
targetPath + "decrypted.txt",
pubkeyPath);
FileStream fs = File.Open(s, FileMode.Open);
test.decrypt(fs, targetPath + "decrypted.txt");
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(archivePath, fileName);
System.IO.File.Move(s, archivePath);
}
}
}

Where are you getting the error. If you are getting error while moving it might be because your filestream is not close. After decryption and before move close the filestream with fs.Close();

I believe the issue you are having is caused by the file not being closed, when you loop with the foreach loop the first iteration probably works. However, the next time, because it was never closed, it is still being used.
Try adding
fs.Close();
At the end of the foreach loop

This is I ended up and it is working
//Decrypt
using DidiSoft.Pgp;
PGPLib pgp = new PGPLib();
string inputFileLocation = file Location;
string privateKeyLocation = #"I posted my private at this location";
string privateKeyPassword = "Decryption Password";
string outputFile = #"Output Location";
// decrypt and obtain the original file name
// of the decrypted file
string originalFileName =
pgp.DecryptFile(inputFileLocation,
privateKeyLocation,
privateKeyPassword,
outputFile);
//Move decrypted file to archive
string path = Decrypted file Location;
string path2 = #"Archive file location" + Path.GetFileName(file); ;
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) { }
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
}
catch (Exception e)
{
}

Related

Xamarin.Forms Deleting Files at Runtime iOS

I need to store a byte[] in memory. I need to access it later. The byte[] represents a video. The following code will allow the file to be written to memory, as well as accessed from memory. When the remove method shown below is called, it can still be accessed later.
I have checked that the pathname is the same.
public void StoreVideo(byte[] video, string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
Directory.CreateDirectory(directoryname);
var path = Path.Combine(directoryname, filename);
File.WriteAllBytes(path, video);
}
public void RemoveVideo(string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
var path = Path.Combine(directoryname, filename);
File.Delete(filename);
}
public byte[] GetVideo(string filename)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directoryname = Path.Combine(documents, "Videos");
var path = Path.Combine(directoryname, filename);
if(File.Exists(path))
{
return File.ReadAllBytes(path);
}
return null;
}
The answer to this was just a small brain fart on the path being passed to the File.Delete method. However for those who run into this you should be aware that File.Delete DOES NOT throw any exception if it cannot delete the file. It should be good practice to wrap the File.Delete method a check for File.Exists

How to delete Zip file after copying into another folder

how to delete a zip file after copying into another folder...I am getting exception while deleting..It is saying that "The file is being used by another process".
string pathString1 = FullFilePath;
string sourceFileName = Path.GetFileName(pathString1);
string foldername = Path.GetDirectoryName(pathString1);
string pathString = Path.Combine(foldername, "Uploaded");
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
string destFile = System.IO.Path.Combine(pathString, sourceFileName);
File.Copy(pathString1, destFile);
File.Delete(pathString1);
File.Delete(FileName);
}
If you decompress the zip-file, then do this in a using block or .Dispose() the object that is responsible for decompressing. What lib are you using?
To prevent the locking of files, the using statement will release the file when it's done with the operation:
using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
...
}
Then again, if you're deleting the file right after you copy it, then why not just move it?
File.Move(from, to);
since there is this theory that a virus checker goes into your .zip file, you could re-try waiting for it to finish with retries
string pathString1 = FullFilePath;
string sourceFileName = Path.GetFileName(pathString1);
string foldername = Path.GetDirectoryName(pathString1);
string pathString = Path.Combine(foldername, "Uploaded");
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
string destFile = System.IO.Path.Combine(pathString, sourceFileName);
File.Copy(pathString1, destFile);
int itries = 0;
int maxtries = 30; //suitable time of retrying
while (itries++ < maxtries)
{
try
{
File.Delete(pathString1);
itries = 999999;
}
catch (Exception ex)
{
if (itries > maxtries) throw ex;
Thread.Sleep(1000);
}
}
//File.Delete(FileName);
}

C# unzip a file: Error with 'Thumbs.db'

I wrote a program that unzip a file (.zip) using SharpZipLib...
The following code:
public void UnZip(string zipFilePath, string extractionPath)
{
FastZip fz = new FastZip();
fz.ExtractZip(zipFilePath, extractionPath, null);
}
I get the following Exception:
Additional information: The access to the path "C:\Program files (x86)\... Thumbs.db" was refused.
The program starts with Admin rights and the file "Thumbs.db" does not exist in the .zip archive.
Who knows further?
Greets and thanks!
I would ignore the "Thumbs.db" file as its an OS file.
Maybe something like this:
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
public void ExtractZipFile(string archiveFilenameIn, string password, string outFolder) {
ZipFile zf = null;
try {
FileStream fs = File.OpenRead(archiveFilenameIn);
zf = new ZipFile(fs);
if (!String.IsNullOrEmpty(password)) {
zf.Password = password; // AES encrypted entries are handled automatically
}
foreach (ZipEntry zipEntry in zf) {
if (!zipEntry.IsFile) {
continue; // Ignore directories
}
String entryFileName = zipEntry.Name;
// to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
// Optionally match entrynames against a selection list here to skip as desired.
// The unpacked length is available in the zipEntry.Size property.
byte[] buffer = new byte[4096]; // 4K is optimum
Stream zipStream = zf.GetInputStream(zipEntry);
// Manipulate the output filename here as desired.
String fullZipToPath = Path.Combine(outFolder, entryFileName);
string directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0)
Directory.CreateDirectory(directoryName);
// Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
// of the file, but does not waste memory.
// The "using" will close the stream even if an exception occurs.
using (FileStream streamWriter = File.Create(fullZipToPath)) {
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
} finally {
if (zf != null) {
zf.IsStreamOwner = true; // Makes close also shut the underlying stream
zf.Close(); // Ensure we release resources
}
}
}

Opening a File in C# using FileStream

I am trying to open a Binary file that I plan on converting to hex but I am running into issues with reading the file via FileStream,
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName); // Returns the proper directory with which to refernce the file
richTextBox1.Text += dirName;
richTextBox1.Text += chosenFile;
FileStream InputBin = new FileStream(
directoryPath, FileMode.Open, FileAccess.Read, FileShare.None);
}
}
I am receiving an error saying that the access to the path is denied, any ideas?
Now that I have gotten that error taken care of I have ran into another Issue, I can read the binary file, but I want to display it as a Hex file, I'm not sure what I am doing wrong but I'm not getting an output in HEX, it seems to be Int values...
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += data[printCount];
printCount++;
}
Your code is miscommented
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
is not the filename, it's the directory path. You want:
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
Addtionally, if I were to guess based on your intentions, you should update your full function to be:
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
richTextBox1.Text += chosenFile; //You may want to replace this with = unless you mean to append something that is already there.
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
}
}
To answer your second quesiton:
I am receiving an error saying that the access to the path is denied,
any ideas?
Now that I have gotten that error taken care of I have ran into
another Issue, I can read the binary file, but I want to display it as
a Hex file, I'm not sure what I am doing wrong but I'm not getting an
output in HEX, it seems to be Int values...
Modify to use string.Format:
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += string.Format( "{0:X} ", data[printCount];
printCount++;
}
}
I've included an ideone example.

How to open file .txt with using openFileDialog in c#?

I have to open and read from a .txt file, here is the code I'm using:
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "F:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var compareType = StringComparison.InvariantCultureIgnoreCase;
var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
var extension = Path.GetExtension(openFileDialog1.FileName);
if (extension.Equals(".txt", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetFullPath(file); //when i did it like this it's work fine but all the time give me same path whatever where my "*.txt" file is
//Insert code to read the stream here.
//fileName = openFileDialog1.FileName;
StreamReader reader = new StreamReader(path);
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}
}
// Exception thrown: Empty path name is not legal
catch (ArgumentException ex)
{
MessageBox.Show("Error: Could not read file from disk. " +
"Original error: " + ex.Message);
}
}
else
{
MessageBox.Show("Invaild File Type Selected");
}
}
The code above throws an exception which says "Empty path name is not legal".
What am I doing wrong?
As pointed by hmemcpy, your problem is in the following lines
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(file);
StreamReader reader = new StreamReader(path);
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}
I'm going to break down for you:
/*
* Opend the file selected by the user (for instance, 'C:\user\someFile.txt'),
* creating a FileStream
*/
using (myStream = openFileDialog1.OpenFile())
{
/*
* Gets the name of the the selected by the user: 'someFile.txt'
*/
string file = Path.GetFileName(openFileDialog1.FileName);
/*
* Gets the path of the above file: ''
*
* That's because the above line gets the name of the file without any path.
* If there is no path, there is nothing for the line below to return
*/
string path = Path.GetDirectoryName(file);
/*
* Try to open a reader for the above bar: Exception!
*/
StreamReader reader = new StreamReader(path);
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}
What you should do is to cahnge the code to something like
using (myStream = openFileDialog1.OpenFile())
{
// ...
var reader = new StreamReader(myStream);
// ...
}
You want user to select only .txt files?
Then use the .Filter property, like that:
openFileDialog1.Filter = "txt files (*.txt)|*.txt";
Your bug is in the lines:
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(file);
In the first line the file variable will only contain the file name, e.g. MyFile.txt, making the second line return an empty string to the path variable. Further down your code you'll attempt to create a StreamReader with an empty path, and this what throws the exception.
By the way, this is exactly what the exception tells you. If you remove the try..catch around the using block, you would've seen it happen during debug in your Visual Studio.
StreamReader accepts Stream type of object while you are passing it a string.
try this,
Stream myStream;
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string file2 = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(myStream);
while (!reader.EndOfStream)
{
MessageBox.Show(reader.ReadLine());
}
MessageBox.Show(openFileDialog1.FileName.ToString());
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}

Categories

Resources