该进程无法访问该文件

时间:2013-08-22 15:41:50

标签: .net visual-studio-2010 io cryptography c++-cli

请查看以下代码

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);
    }


}

当执行以下部分时,我收到错误

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

以下是我得到的错误

enter image description here

这是我第一次使用CryptoStream,而且我也是C ++ / CLI的新手。

1 个答案:

答案 0 :(得分:2)

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

您打开文件两次,一次输入,一次输出。你在这里有几个选择:

  1. 打开启用共享的文件,允许您打开两次。
  2. 打开文件,将整个文件读入内存,关闭文件,然后打开 输出文件并进行加密。
  3. 打开一个临时文件 输出,在那里写入所有数据,然后重命名临时文件 原始文件的顶部。