tags:

views:

46

answers:

1

Hey all,

I'm attempting to read a binary file and I keep getting errors on 64-bit systems where it appears that the file is being open with write privileges and thus throws an error when placed in a secure folder (Program Files in 64 bit Windows). I can duplicate this error on my system (XP, 32 bit) by setting the folder containing the documents to be read to read-only.

Here's the code I'm using:

    public static byte[] GetContentFromFile(string file)
    {
        try
        {
            FileStream stream = new FileStream(String.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, file), FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(stream);

            byte[] content = new byte[stream.Length];

            reader.Read(content, 0, content.Length);

            reader.Close();
            stream.Close();

            return content;
        }
        catch
        {
            return new byte[0];
        }
    }

Any ideas?

A: 

Put this file in an AppData folder instead?

It may help to know the exact exception being thrown. UnauthorizedAccessException is thrown when a read-only file is opened for writing, while SecurityException is thrown if the code is running in an app domain that doesn't have permissions to open that file in the specified mode. The first will thus only happen if you really are trying to write to a read-only file, while the second can happen if the user or code can't even read it.

Also, just a shot in the dark, try specifying a FileShare value of Read, which will allow other threads/processes to read the file as well. The default is None, which locks all other access to the file and may be causing a problem if Windows thinks a full lock somehow equates to write access.

KeithS