24

The MSDN constructor for a FileStream says that it may throw either an UnauthorizedAccessException or a SecurityException. Here's what MSDN says about these exceptions.

UnauthorizedAccessException: The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error.

SecurityException: The exception that is thrown when a security error is detected.

How are these two similar exceptions different? What situations will trigger either of them?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Eric Anastas
  • 21,675
  • 38
  • 142
  • 236

1 Answers1

14

A UnauthorizedAccessException is thrown when there is a permissions error accessing the file on disk. That is an error at the operating system level such as a normal user trying to overwrite an operating system file (like kernel32.dll).

A SecurityException is thrown if there is a security violation at the CLR level. For example if you are running as a low access ClickOnce application and attempt to read / write to a place in the file system forbidden by the CLR security settings in the process.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • So if I tried to write/create a file on a network drive which the current user does not have write access to then it would throw a UnauthorizedAccessException? – Eric Anastas Feb 26 '10 at 03:32
  • Please add some more description or example to understand how they actually differ? – Nirav Kamani Mar 10 '14 at 04:41
  • 1
    `SecurityException` is thrown by some in-box APIs like `RegistryKey.OpenBaseKey` (which also throws `UnauthorizedAccessException`, confusingly). – Dai Nov 15 '18 at 06:02