Reputation: 2203
I've created a c# .net(4.5) command line application. This application does nothing, but stay open:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("started");
Console.ReadLine();
}
}
If i navigate to this file in explorer, i can rename it with F2 while the program is running.
If i try to delete it, a message is shown:
I can understand that it is not possible to delete a loaded assembly. Move the loaded assembly from one folder to another doesn't work either.
But why can it be renamed?
Is this intended? Is there a use case to rename an existing/loaded assembly?
Upvotes: 4
Views: 1236
Reputation: 2203
Imo best answer so far from https://superuser.com/questions/488127/why-can-i-rename-a-running-executable-but-not-delete-it
There really is no such thing as renaming a file. A file can have more than one name or no name, so it's not the file that you're renaming but the directory entry. Renaming is an operation on the directory entry, which is not affected by the fact that the file is locked for execution.
Upvotes: 1
Reputation: 941218
Files are represented in the file system by two major structures. First is the directory entry, it stores metadata about the file. Like the file name, size, attributes and time stamps. Next is the chain of clusters that store the file data.
Loading an assembly causes a memory mapped file to be created for the assembly. An optimization, it ensures that you only pay for the parts of the assembly you'll actually use. The file data won't be read into RAM until it is actually needed. A core feature of a demand-paged virtual memory operating system like Windows.
The memory mapped file puts a lock on the file to ensure the file data cannot be changed by another process. That would be disastrous, the data in RAM would not match the data in the file anymore. Locks in Windows only protect the file data, not the metadata for the file. Or in other words, you can still modify the directory entry for the file, as long as that doesn't also modify the file data.
So renaming the file is not a problem, that only modifies the directory entry. Even moving the file from one directory to another is not a problem, that only changes the location of the directory entry, it doesn't modify the file data as long as file is large enough to require clusters. Moving the file from one drive to another is a problem since that requires a copy that also deletes the original file data. Deleting the file is not possible, that also deletes the file data.
Upvotes: 11
Reputation: 4519
Renaming doesn't change much in terms of what is written on disk, in fact it likely only changes the file allocation tables and some file meta.
For this reason, the chunk of disk containing the program is still available to be copied into memory or executed despite the change of name.
Upvotes: 0