Check if a file that's not locked is open
Some programs (image programs such as Paint, text editors such as notepad and Wordpad,and others) open files, load the contents into memory, then release the file lock. Is there a way to tell if a program is using that file even though it's not locked?
For example, even if image1.bmp is open in Paint, my program can overwrite the copy of image1.bmp that's on the disk because the file isn't locked. Now the copy of image1.bmp that is open in Paint is different than the copy of image1.bmp that is on the disk.
My program is written in C#. I usually use this method for checking if a file is locked, but it won't work in the above case. Is there a way to check if a file is in use?
Is there any solution to this?
"Now the copy of image1.bmp that is open in Paint" - here's your mistake - the file is no longer open in Paint. It was opened, read, and then closed. Paint does not keep the file open at all - it only has a COPY of its contents in RAM memory. To put it in another way - the fact that you see a picture in MS Paint doesn't mean the file is open.
It is comparable to loaning a document to someone, then he makes a photocopy and returns it - that person no longer "holds" the document, he has a separate copy of it. And there is no way, just by looking at the document, to know who might have made a copy of it at some point in history.
Another way of putting it is this pseudocode:
File file = Open("image.png");
Image img = ImageFromFile(file);
file.Close();
...
img.Save("image.png");
Here no file is being opened at all, there's just a copy in RAM of its content.
Note: I actually checked that for Paint - Process Explorer can show you opened handles, I opened a file in Paint and there was no handle at all listed for a file of that name.
Here's what I came up with. I check all open processes for a window title. If the process has a window title, I see if it contains the name of the file I'm looking for.
It won't work 100% of the time since some applications can have multiple files open in a single instance.
I adapted it from this question:Getting a list of all applications
bool isFileOpen(string file)
{
string windowTitle = "";
Process[] myProcesses = Process.GetProcesses();
foreach (Process P in myProcesses)
{
if (P.MainWindowTitle.Length > 1)
{
windowTitle = P.MainWindowTitle;
if (windowTitle.Contains(file) == true)
{
return true;
}
}
}
return false;
}
链接地址: http://www.djcxy.com/p/40558.html
上一篇: Django在Apache / mod上运行时出错
下一篇: 检查未锁定的文件是否已打开