Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7927503
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T19:20:05+00:00 2026-06-03T19:20:05+00:00

At first I thought I’m facing a very simple task. But now I realized

  • 0

At first I thought I’m facing a very simple task. But now I realized it doesn’t work as I imagined, so now I hope you people can help me out, because I’m pretty much stuck at the moment.

My scenario is this (on a Windows 2008 R2 Server):

  1. A file gets uploaded 3 times per day to a FTP directory. The filename is always the same, which means the existing file gets overwritten every time.
  2. I have programed a simple C# service which is watching the FTP upload directory, I’m using the FileSystemWatcher class for this.
  3. The upload of the file takes a few minutes, so once the File Watcher registers a change, I’m periodically trying to open the file, to see if the file is still being uploaded (or locked)
  4. Once the file isn’t locked anymore, I try to move the file over to my IIS Virtual Directory. I have to delete the old file first, and then move the new file over. This is where my problem starts. The file seems to be always locked by IIS (the w3wp.exe process).

After some research, I found out that I have to kill the process which is locking the file (w3wp.exe in this case). In order to do this, I have created a new application pool and converted the virtual directory into an application. Now my directory is running under a seperate w3wp.exe process, which I supposedly can safely kill and move the new file over there.

Now I just need to find the proper w3wp.exe process (there are 3 w3wp.exe processes running in total, each running under a seperate application pool) which has the lock on my target file. But this seems to be an almost impossible task in C#. I found many questions here on SO regarding “Finding process which locked a specific file”, but none of the answers helped me.
Process Explorer for example is exactly telling me which process is locking my file.

The next thing I don’t understand is, that I can delete the target file through Windows Explorer without any problem. Just my C# application gets the “File is being used by another process” error. I wonder what’s the difference here…

Here are the most notable questions on SO regarding locked files and C#:

Win32: How to get the process/thread that owns a mutex?

^^
The example code here does actually work, but this outputs the open handle IDs for every active process. I just can’t figure out how to search for a specific filename, or at least resolve the handle ID to a filename. This WinAPI stuff is way above my head.

Using C#, how does one figure out what process locked a file?

^^
The example code here is exactly what I need, but unfortunately I can’t get it to work. It is always throwing an “AccessViolationException” which I can’t figure out, since the sample code is making extensive use of WinAPI calls.

Simple task, impossible to do? I appreciate any help.

EDIT
Here are some relevant parts of my server code:

Helper function to detect if a file is locked:

    private bool FileReadable(string file, int timeOutSeconds)
    {
        DateTime timeOut = DateTime.Now.AddSeconds(timeOutSeconds);

        while (DateTime.Now < timeOut)
        {
            try
            {
                if (File.Exists(file))
                {
                    using (FileStream fs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        return true;
                    }
                }
                return false;
            }
            catch (Exception)
            {
                Thread.Sleep(500);
            }
        }

        m_log.LogLogic(0, "FileReadable", "Timeout after [{0}] seconds trying to open the file {1}", timeOutSeconds, file);
        return false;
    }

And this is the code in my FileSystemWatcher event, which is monitoring the FTP upload directory. filepath is the newly uploaded file, targetfilepath is the target file in my IIS directory.

        // here I'm waiting for the newly uploaded file to be ready
        if (FileReadable(filepath, FWConfig.TimeOut))
        {
            // move uploaded file to IIS virtual directory
            string targetfilepath = Path.Combine(FWConfig.TargetPath, FWConfig.TargetFileName);

            if(File.Exists(targetfilepath))
            {
                m_log.LogLogic(4, "ProcessFile", "Trying to delete old file first: [{0}]", targetfilepath);
                // targetfilepath is the full path to my file in my IIS directory
                // always fails because file is always locked my w3wp.exe :-(
                if(FileReadable(targetfilepath, FWConfig.TimeOut))
                    File.Delete(targetfilepath);
            }

            File.Move(filepath, targetfilepath);
        }

EDIT2:
Killing the w3wp.exe process while clients are downloading the file would be no problem for us. I’m just having a hard time finding the right w3wp.exe process which is locking the file.

Also, my client application, which is downloading the file on the clients, is checking the HTTP HEAD for the Last-Modified date. The client is checking the date every 10 minutes. So it is possible that the file is being locked by IIS because there are clients continously checking the HTTP HEAD for the file. Nonetheless, I don’t understand why I can manually delete/rename/move the file through windows explorer without any problems. Why does this work, and why does my application get a “Locked by another process” exception?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T19:20:08+00:00Added an answer on June 3, 2026 at 7:20 pm

    One problem I’ve run into is that a file exists while it is still being written, which means it would be locked as well. If your FileReadable() function were called at this time, it would return false.

    My solution was to, in the proc which writes the file, write the file to, say, OUTPUT1.TXT, and then after it is fully written and the FileStream closed, rename it to OUTPUT2.TXT. This way, the existence of OUTPUT2.TXT indicates that the file is written and (hopefully) unlocked. Simply check for OUTPUT2.TXT in your FileReadable() loop.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Okay at first I thought this would be pretty straightforward. But I can't think
here's the main code at first I thought is was the message box but
I very rarely meet any other programmers! My thought when I first saw the
What is the reason null doesn't evaluate to false in conditionals? I first thought
First thought of implementing this using threads but python doesnt have a way for
This is actually not as simple as I first thought. In the absence of
I am making an Android application. Since it is so simple, I first thought
So I know the first thought is Sticky Footer, but that's not really the
So, this seemed simple at first, but after crawling Google and here, the answer
I need to create a heterogeneous List of objects (custom classes). My first thought

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.