0

I try to copy a file that is included in the app bundle as a resource to the temp folder on the iPhone. While this works on the Simulator, on the device I get an exception:

System.UnauthorizedAccessException: Access to the path "/private/var/mobile/Applications/B763C127-9882-4F76-8860-204AFEA8DD68/Client_iOS.app/testbundle.zip" is denied.

The code I use is below It cannot open the source file.

using(var sourceStream = File.Open("./demobundle.zip", FileMode.Open))
{
    sourceStream.CopyTo(targetStream);
}   

What is the correct way of copying a file into a destination stream?

admdrew
  • 3,790
  • 4
  • 27
  • 39
Krumelur
  • 32,180
  • 27
  • 124
  • 263

1 Answers1

3

Why is it that I always find the answers to my questions practically immediately after I asked here? :-)

One has to specify the file access mode. If it is set to Read, it'll work. The default seems to be some write mode and that is obviously not possible.

using(var sourceStream = File.Open("./demobundle.zip", FileMode.Open, FileAccess.Read))
{
    sourceStream.CopyTo(targetStream);
}
Krumelur
  • 32,180
  • 27
  • 124
  • 263
  • 1
    [`File.Open`](http://msdn.microsoft.com/en-us/library/y973b725%28v=vs.110%29.aspx) will return an `UnauthorizedAccessException` for read-only files if you don't explicitly add `FileAccess.Read`. – admdrew May 19 '14 at 18:08
  • 1
    It's one of the reason why Gendarme has a rule that ask you to always specify the `FileMode` and `FileAccess`. The defaults are not always what the developers expect and often differs on the execution (customer or device in this case) environment. – poupou May 20 '14 at 13:34