title: Setting the last-modified-time of a directory opened for ReadDirectoryChangesW
body: <p>I hava a Java program that needs to monitor a directory tree for changes.  I have JNI code that uses <code>ReadDirectoryChangesW()</code>.  The directory is opened like:</p>
  
  <pre><code>HANDLE dirHandle = CreateFile(
      path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
      OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL
  );
  </code></pre>
  
  <p>and then I pass <code>dirHandle</code> to <code>ReadDirectoryChangesW()</code>.  All of that works just fine.</p>
  
  <p>The problem is that other parts of the code (on the Java side) use <code>File.setLastModified()</code> to "touch" files or directories (update their timestamps to be "now").  This generally works; however, it fails when it tried to "touch" the directory that was opened using <code>CreateFile()</code>.</p>
  
  <p>To see what Windows error is actually occurring, I looked at the JDK source for <code>File.setLastModified()</code> and reimplemented it in my own code with the addition of printing the error from <code>GetLastError()</code>; the error is:</p>
  
  <pre><code>ERROR_SHARING_VIOLATION (error 32)
  "The process cannot access the file because it is being used by another process."
  </code></pre>
  
  <p>WTF?  It's the <em>same</em> process. I even passed <code>FILE_SHARE_READ</code> and <code>FILE_SHARE_WRITE</code> to <code>CreateFile()</code>.</p>
  
  <p>Is there a way to make this work?</p>
  
  <h2>More Info</h2>
  
  <p>The native code implementation of <code>File.setLastModified()</code> in the JDK does a:</p>
  
  <pre><code>h = CreateFileW(pathbuf, GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
                  FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, 0);
  </code></pre>
  
  <p>If I change the first <code>0</code> to <code>FILE_SHARE_READ | FILE_SHARE_WRITE</code>, it all works.  So it seems that the JDK implementation is a little broken. :(</p>
  
  <p>So my question now becomes: Is there a way to make this work without having to use my own (re)implementation of <code>File.setLastModified()</code>?</p>