Tutorial :.net security exception


I am using OpenFileDialog class to browse a file in window application using c#. It is giving the security exception as below.

Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

My code is

        OpenFileDialog fdlg = new OpenFileDialog();          fdlg.Title = "C# Corner Open File Dialog";          fdlg.InitialDirectory = @"c:\";          fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";          fdlg.FilterIndex = 2;          fdlg.RestoreDirectory = true;          if (fdlg.ShowDialog() == DialogResult.OK)          {              txtpath.Text = fdlg.FileName;          }  

I am not getting the problem. please help.


Security Note
To get or set the FileName property, your assembly requires a privilege level granted by the System.Security.Permissions.FileIOPermission class. If you are running in a partial-trust context, the process might throw an exception due to insufficient privileges. For more information, see Code Access Security Basics.


If you are actually trying to run this code from an ASP.NET application, then the exception you receive makes sense. This is Windows Forms code, and is not meant to run in an ASP.NET application.

Among other things, ASP.NET applications run in a reduced-trust environment. They are not allowed to do certain things that a "normal" application can do.

.NET includes a concept called "Code Access Security". It grants different access to different .NET features depending on things like where the code comes from. Naturally, code running from your computer is more trusted that code running from some other computer. In your environment, that means it's not trusted to access the file system in this manner.

This code will need to be copied to a local drive and run from there.


For desktop app, please check your project properties "Security" setting, to make sure disable the ClickOnce security settings. Good luck!

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »