How to lock up a file

I am writing some C# code which processes a set of files in a source directory and then moves the files to a destination directory. The code must be able to handle a situation in which one of the files might become locked while the files are being processed. I am not concerned at this point with how to handle the exception when a particular file is locked.

What I need to know is how can I lock up the file You see, I must test my code against a file that is locked up. I tried locking up a file by selecting it, and then right clicking on the file and selecting rename. I also tried opening the file for edit. Neither of these two methods will lock up the file.

Can anyone tell me if there is a way to lock up a file



Answer this question

How to lock up a file

  • Malicious User

    Thank you !. Now, conversely, is their a way with C# to progromatically test if a file is locked up by another application


  • Scott Koo

    As MarcD already said, if you want to lock some file you can open it in some other app in this way:
    FileStream fs = File.Open(@"C:\test.txt", FileMode.Open)
    and until you don't make fs.Close() in this app, other apps can't use this file.


  • Dieter Depuydt

    If you haven't heard yet, the new Transactional NTFS filesystem (and registry for that matter) have helped out extremely for testers of cases such as these. If you haven't, check out this MSDN On Demand Webcast, presented by Dana Groff, the Program Manager of Microsoft.

  • JPR7

    You can't find out if a file is locked until you try to access it. I think this is by design; if you could, it might get locked between the time you checked it and accessed it. Catch System.IO.IOException to detect the lock.


  • Jonathan1983

    Open up the file in any MS Office application. Or have another application that opens the file and doesn't close it till you're done.

  • How to lock up a file