1

I am trying to overwrite a file's contents. That file is in use in most of the cases. I know how to do this in Java, but I am not sure how to do this in C#. That's what I currently have:

    public bool ByteArrayToFile(string fileName, byte[] byteArray)
    {
        try
        {
            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                fs.Write(byteArray, 0, byteArray.Length);
                return true;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught in process: {0}", ex);
            return false;
        }
    }

I am trying to write a byte array to a file. I get the byte array from an URL, using a WebClient. When the file's in use, I get an IOException, which says that I can't access the file because it's being used by another process. In Java, I'd do it like this, using commons-io:

FileUtils.copyInputStreamToFile(new URL(url).openStream(), target);

The method above has worked for me, but I can't seem to replicate it in C#. Is there a way to do it?

  • 1
    You cannot leave out the FileShare argument in a case like this. Find a decoder ring in [this post](https://stackoverflow.com/a/25098500/17034). – Hans Passant May 26 '18 at 13:30
  • What would be a good FileShare argument in this case? – Tsvetomir Bonev May 26 '18 at 15:07
  • None that I know of, this normally confuses the stuffing out of the other process when it doesn't expect the file data to change randomly. Especially detrimental when it happens while it is busy reading the file. But FileShare.Read would be a starting point if that somehow doesn't happen. FileShare.ReadWrite removes all obstacles. – Hans Passant May 26 '18 at 15:14
  • If, by chance, the other processes opened the file with FileShare.Delete (FILE_SHARE_DELETE), you might rename the file and create a new one with the original filename. – grepfruit May 26 '18 at 19:28

1 Answers1

0

You cannot overwrite a file in use and locked by another process in Windows. You'd need to find the process which has a handle to the file and terminate the process in order to release the handle.

If you are writing or controlling the programs/processes accessing the files, perhaps look into using something like the following from System.IO:

FileStream.Lock - 'Prevents other processes from reading from or writing to the FileStream'

FileStream.Unlock - 'Allows access by other processes to all or part of a file that was previously locked.'

Stringfellow
  • 2,788
  • 2
  • 21
  • 36