Visual Studio breakpoints -- break on specific file access

What I would do is just quickly hack up a static class that uses the FileSystemWatcher class to listen to file create/changed events, and put a breakpoint in the event callback, or put a call to System.Diagnostics.Debugger.Break there.

Then, when it breaks, switch to the Threads window and try to locate the thread and the piece of code that did the actual file-access.

If you need to use this a lot, have this class maintain a list of specific file names you want to break on, and expose two public static methods: to Start and Stop listening to changes in a specific file.

Also, if you have VS2010 Ultimate you could simply search through the list of File Created events in the IntelliTrace events log.


If you're interested in any access to the file, rather than just writes to it, FileSystemWatcher won't help.

A simple solution is to open the file in advance and wait for the other logic to access it, triggering an IOException. You can use the following helper class to break immediately - or VS's "First Chance Exception" feature:

using System;
using System.Diagnostics;
using System.IO;
using System.Threading;

static class DebugHelper
{
    public static void BreakOnFileAccess(string path) 
    {
        var msg = Path.GetFullPath(path);
        msg = "The process cannot access the file '" + msg;
        msg = msg.ToUpper();

        var fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
        new Thread(() => {
            while (true) 
            {   
                Thread.Sleep(Timeout.Infinite);
                // ensure FileStream isn't GC'd as a local variable after its last usage
                GC.KeepAlive(fs);
            }
        }).Start();

        AppDomain.CurrentDomain.FirstChanceException += (sender, e) => {
            if (e.Exception is IOException && 
                e.Exception.Message.ToUpper().Contains(msg))
            {
                Debugger.Break();
            }
        };
    }
}