如何删除为普通 I/O 打开的文件?
我想解密文件。如果代码不正确,那么我需要删除输出文件。
我不能使用 File.Delete()
因为:
Windows NT 4.0 平台注意:删除不会删除为正常 I/O 打开的文件或内存映射的文件。
try
{
FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read, FileShare.Delete);
FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Delete);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
Rijndael alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write);
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;
do
{
bytesRead = fsIn.Read(buffer, 0, bufferLen);
cs.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
cs.Close();
fsIn.Close();
return true;
}
catch(Exception)
{
MessageBox.Show("Incorrect code :(");
return false;
}
有人知道如何删除输出文件吗?
最佳答案
答案已经在你的问题中。
Delete does not delete a file that is open for normal I/O.
所以,关闭文件,然后你就可以删除它了。
您还应该将文件流包装在 using
block 中,以确保及时且可预测的方式整理非托管资源。像这样:
using (FileStream fsIn = new FileStream(...))
{
....
}
这是确保您的文件在您完成处理后关闭的最佳方式。您可以在 using
block 之后调用 File.Delete
。
最后,我很确定您不想使用 FileShare.Delete
。例如,在您的输入文件上,将允许其他进程在您对其进行操作时删除该文件。您希望对正在读取的文件使用 FileShare.Read
,对正在写入的文件使用 FileShare.None
。
关于c# - 如何删除为正常 I/O 打开的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13902763/