When I enter the name of the file to be saved, it gives me an error: the process cannot access the files (directory+name of fileout) Because it is being used by another process. Why? How can I solve?
private void button_Click_C_Open(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
//openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
filein = openFileDialog1.FileName; //file in lo scegliamo dal openfiledialog
textFileScelto.Text = filein; //visualizza la scelta in una textbox
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
private void Encypt_File_Click(object sender, EventArgs e)
{
try
{
Stream my1Stream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((my1Stream = saveFileDialog1.OpenFile()) != null)
{
fileout = saveFileDialog1.FileName;
passwordBytes = GetPasswordBytes();
AES.EncryptFile(filein, fileout, passwordBytes);
MessageBox.Show("File Criptato!");
my1Stream.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I apologize for any grammatical mistakes.I hope I understand well your answers. Thanks in advance.
Your own application holds a lock to the file because of the OpenFile() method. Try to put
my1Stream.Close();
beforeAES.EncryptFile(filein, fileout, passwordBytes);
.There is actually no need to use the stream.
This should do the trick
There is no easy solution for this. You need to figure out which process has the filter open and either stop that process or get the order to exit it.
But most importantly you need to handle the exception in your code.
Figuring which process is using the filter programmatically is a non trivial task.