-1

I have the following C# code:

static void Main(string[] args)
    {
        FileStream fileStream = null;
        try
        {
            // read from file or write to file
            fileStream = new FileStream(@"D:\FileLock.txt", FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch
        {
        }
        finally
        {
            fileStream.Close();
        }
    }

and I'm trying to copy the file "D:\FileLock.txt" to another location using the following C (WinAPI) code:

CopyFile(_T("D:\\FileLock.txt"), _T("D:\\temp\\FileLock.txt"),FALSE);

But I get ERROR_SHARING_VIOLATION (as expected).

Is there anyway I can bypass this? (i.e. copy the file under these conditions) --without modifying the C# code

conectionist
  • 2,694
  • 6
  • 28
  • 50

2 Answers2

-1

If you can change the C# code, then this should work (changed the OP code to use FileShare.Read):

static void Main(string[] args)
{
    using (FileStream fileStream = new FileStream(@"D:\FileLock.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
    {
    }
}
Polyfun
  • 9,479
  • 4
  • 31
  • 39
-2

Upon further research, it would seem that this is possible by writing a driver and using some low level functions.

conectionist
  • 2,694
  • 6
  • 28
  • 50
  • 2
    Please don't. The sharing mechanism is designed to protect the integrity of both the system and apps running on it. Please go back and tell us why you need to "bypass a sharing violation", what program isn't playing nice, and why modifying the source is out of the question. – andlabs Feb 13 '15 at 16:44