【问题标题】:The process cannot access the file because it is being used by another process #2该进程无法访问该文件,因为它正被另一个进程使用 #2
【发布时间】:2012-12-24 20:23:05
【问题描述】:

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

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

有什么想法吗?

【问题讨论】:

  • 请停止使用匈牙利符号。这是一个建议:)

标签: c#


【解决方案1】:

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

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

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

相关

【讨论】:

  • StreamWriter dirBackup = new StreamWriter(dirBackupPath, false, Encoding.UTF8); dirBackup.WriteLine(strDirectoryEncryptedData); dirBackup.Close(); 更改为 using (StreamWriter dirBackup = new StreamWriter(dirBackupPath, false, Encoding.UTF8)) { //write line here } 仍然出现错误。
  • @user1927274:虽然我认为你提出的改变是一个非常好主意,你绝对应该这样做,但我不认为它是与给您当前问题的问题有关。请再次阅读我的回答 - 它指的是 StreamReader,而不是 StreamWriter
  • 但我在 StreamWriter 中收到错误,而不是在 StreamReader.. StreamReader 无法收到任何错误,因为它在当前时间未使用。
  • 哦等等..我有..StreamReader 打开文件,这就是为什么StreamWriter 无法访问...谢谢!
猜你喜欢
  • 2010-12-10
相关资源
最近更新 更多