问题
Hi guys I need some help. I'm trying to open a textfile on a servern from multiple clients at the same time so I'm not locking the file when reading from it. Like this:
new StreamReader(File.Open(logFilePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
Now I'm trying to check if this file is used by any of the clients (because I want to write something new to it), but since I'm not locking it when reading from it I don't know how to do this. I can't try to open and catch an exception because it will open.
回答1:
I can't try to open and catch an exception because it will open
Why ? It's a valuable option to work in that way.
By the way you can also create a some empty predefined file, say "access.lock", and others, in order to understand if the actual file is locked check on lock file presence:
if(File.Exist("access.lock"))
//locked
else
//write something
回答2:
Do you can try this?
Or watch this question already asked here ->Is there a way to check if a file is in use?
protected virtual bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
来源:https://stackoverflow.com/questions/16031145/check-if-file-is-in-use