2012-12-24 42 views
-1

我正在做一个小小的备份工具......而且我有一个小问题,不知道如何解决这个问题。所以这就是为什么我问这里...代码:该进程无法访问该文件,因为它正在被另一个进程使用#2

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

任何想法?

+0

请停止使用匈牙利命名法。这是一个建议:) – miniBill

回答

4

您没有正确关闭您的资源。您无法打开该文件进行书写,因为您已将其打开以供阅读,但尚未关闭。

当您完成使用它们时,您需要处理您的StreamReader对象。 StreamReader类实现IDisposable。我建议您使用using块,以便即使存在异常时文件也会始终关闭。

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

相关

+0

嗯...让我们试试.. – user1927274

+0

更改'StreamWriter dirBackup =新的StreamWriter(dirBackupPath,false,Encoding.UTF8); dirBackup.WriteLine(strDirectoryEncryptedData); dirBackup.Close(); (StreamWriter dirBackup = new StreamWriter(dirBackupPath,false,Encoding.UTF8)) { //在此处写入行 }并且仍然出现错误。 – user1927274

+0

@ user1927274:虽然我认为你提出的改变是一个非常好的主意,你绝对应该这样做,但我认为这与你提出当前问题的问题没有关系。请再次阅读我的答案 - 它指的是** StreamReader **,而不是'StreamWriter'。 –

相关问题