【问题标题】:The process cannot access the file进程无法访问文件
【发布时间】:2013-08-22 15:41:50
【问题描述】:

请看下面的代码

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

以下是我得到的错误

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

【问题讨论】:

  • 您的代码存在根本缺陷,它不是异常安全的。谷歌“c++/cli stack semantics”学习如何正确编写。
  • @HansPassant:非常感谢您指出问题。我会检查出来:)
  • 请注意,DES 太弱了。 ASCII 键使它更弱。使用密钥作为 IV 也是非常错误的,使用静态 IV 也是如此。

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


【解决方案1】:
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. 打开一个临时文件 输出,将所有数据写入那里,然后重命名临时文件 原始文件的顶部。

【讨论】:

  • 我使用了第三种方法。非常感谢。 Windows 编程对我来说是新的,因为我来自 Java、Android 和 C++
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
相关资源
最近更新 更多