Search code examples
.netvisual-studio-2010iocryptographyc++-cli

The process cannot access the file


Please have a look at the following code

void InformationWriter::writeContacts(System::String ^phone, System::String ^email)
{
    try
    {
        //Write the file
        StreamWriter ^originalTextWriter = gcnew StreamWriter("contacts.dat",false);
        originalTextWriter->WriteLine(phone);
        originalTextWriter->WriteLine(email);
        originalTextWriter->Close();


        //Encrypt the file
        FileStream ^fileWriter = gcnew FileStream("contacts.dat",FileMode::OpenOrCreate,FileAccess::Write);

        DESCryptoServiceProvider ^crypto = gcnew DESCryptoServiceProvider();

        crypto->Key = ASCIIEncoding::ASCII->GetBytes("Intru235");
        crypto->IV = ASCIIEncoding::ASCII->GetBytes("Intru235");

        CryptoStream ^cStream = gcnew CryptoStream(fileWriter,crypto->CreateEncryptor(),CryptoStreamMode::Write);


        //array<System::Byte>^ phoneBytes = ASCIIEncoding::ASCII->GetBytes(phone);
        FileStream ^input = gcnew FileStream("contacts.dat",FileMode::Open); //Open the file to be encrypted
        int data = 0;

        while((data=input->ReadByte()!=-1))
        {
            cStream->WriteByte((System::Byte)data);
        }

        input->Close();
        cStream->Close();
        fileWriter->Close();

        System::Windows::Forms::MessageBox::Show("Data Saved");
    }
    catch (IOException ^e)
    {
        System::Windows::Forms::MessageBox::Show(e->Message);
    }


}

When the following part get executed, I get an error

FileStream ^input = gcnew FileStream("contacts.dat",FileMode::Open); //Open the file to be encrypted

Below is the error I get

enter image description here

This is the first time I am using CryptoStream and I new to C++/CLI as well.


Solution

  • FileStream ^fileWriter = gcnew FileStream("contacts.dat",FileMode::OpenOrCreate,FileAccess::Write);
    
    // snip
    
    FileStream ^input = gcnew FileStream("contacts.dat",FileMode::Open); //Open the file to be encrypted
    

    You're opening the file twice, once for input and once for output. You've got a few choices here:

    1. Open the file with sharing enabled, allowing you to open it twice.
    2. Open the file, read the entire file into memory, close the file, then open the file for output and do the encryption.
    3. Open a temporary file for output, write all the data there, and then rename the temp file over top of the original file.