-1

我正在制作一个小备份工具...而且我有一个小问题,不知道如何解决这个问题。所以我在这里问... 代码:

strDirectoryData = dlg1.SelectedPath;
strCheckBoxData = "true";
clsCrypto aes = new clsCrypto();
aes.IV = "MyIV";     // your IV
aes.KEY = "MyKey";    // your KEY      
strDirectoryEncryptedData = aes.Encrypt(strDirectoryData, CipherMode.CBC);
strCheckBoxEncryptedData = aes.Encrypt(strCheckBoxData, CipherMode.CBC);

StreamWriter dirBackup = new StreamWriter(dirBackupPath, false, Encoding.UTF8);
StreamWriter checkBackup = new StreamWriter(autoBackupPath, false, Encoding.UTF8);
dirBackup.WriteLine(strDirectoryEncryptedData, Encoding.UTF8);
dirBackup.Close();
checkBackup.WriteLine(strCheckBoxData, Encoding.UTF8);
checkBackup.Close();'

每次都出错 - 该进程无法访问该文件,因为它正被另一个进程使用...

我也有这个在 Form1_Load

if (!Directory.Exists(folderPath))
{
    Directory.CreateDirectory(folderPath);
    string strCheckBoxData;
    string strDirectoryData;
    string strCheckBoxEncryptedData;
    string strDirectoryEncryptedData;
    strDirectoryData = "Nothing here";
    strCheckBoxData = "false";
    clsCrypto aes = new clsCrypto();
    aes.IV = "MyIV";     // your IV
    aes.KEY = "MyKey";    // your KEY      
    strDirectoryEncryptedData = aes.Encrypt(strDirectoryData, CipherMode.CBC);
    strCheckBoxEncryptedData = aes.Encrypt(strCheckBoxData, CipherMode.CBC);

    StreamWriter dirBackup = new StreamWriter(dirBackupPath, false, Encoding.UTF8);
    StreamWriter checkBackup = new StreamWriter(autoBackupPath, false, Encoding.UTF8);
    dirBackup.WriteLine(strDirectoryEncryptedData);
    dirBackup.Close();
    checkBackup.WriteLine(strCheckBoxEncryptedData);
    checkBackup.Close();
}
else
{
    string strCheckBoxDecryptedData;
    string strDirectoryDecryptedData;

    StreamReader dirEncrypted = new StreamReader(dirBackupPath);
    StreamReader checkEncrypted = new StreamReader(autoBackupPath);

有任何想法吗?

4

1 回答 1

4

您没有正确关闭资源。您无法打开文件进行写入,因为您已经打开它进行读取但您没有再次关闭它。

使用完对象后,您需要处理StreamReader它们。该类StreamReader实现IDisposable. 我建议你使用一个using块,这样即使出现异常,文件也将始终关闭。

using (StreamReader dirEncrypted = new StreamReader(dirBackupPath)) {
     // read from dirEncrypted here
}

有关的

于 2012-12-24T20:24:56.310 回答