Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public static Boolean IsFileLocked(FileInfo file)
        {
            FileStream stream = null;
            try
            {
                stream = file.Open(FileMode.Truncate, FileAccess.Write, FileShare.None);
                //using (StreamReader reader = new StreamReader(File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
                //{
                //    return false;
                //}
            }
            catch (IOException)
            {
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            return false;
        }

i tried with above code but it's not working
Posted
Comments
José Amílcar Casimiro 3-May-14 6:34am    
Do you want to know if the file is open by your application, or some other process?
teja sai ravi 3-May-14 7:01am    
i want to know is a specified text file is open r not thanks for ur reply

1 solution

If you go back to the original source, which as far as I know is here: http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use[^]
It uses FileMode.Open, not FileMode.Truncate, and FileMode.ReadWrite not FileMode.Write - it's probably worth going back to the original, because that does work.
 
Share this answer
 
Comments
teja sai ravi 3-May-14 7:10am    
it's not working friend can u give another solution ....thanks for ur reply
OriginalGriff 3-May-14 7:19am    
"it's not working" isn't very helpful: What is it doing that you don't expect, or not doing that you do. And how are you testing? How do you know it has not worked?
teja sai ravi 3-May-14 7:25am    
i opened a text file and iam trying to read the same file through code. its executing the try block i think it should come to catch block when the text file is opened but its not coming can u explain the process thanks in advance
OriginalGriff 3-May-14 7:26am    
How did you open it? Show the code you used to open and then check the file.
teja sai ravi 3-May-14 7:29am    
i manually opened the text file and same text file iam trying to opening through code

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900