Home » Development » (Solved) System.UnauthorizedAccessException occurred in mscorlib.dll

(Solved) System.UnauthorizedAccessException occurred in mscorlib.dll

A web application (or SharePoint web part in my case) may throw System.UnauthorizedAccessException error below if the file you are trying to access is not available. The file may not exist or you may not have permissions to access it.

An exception of type “System.UnauthorizedAccessException” occurred in mscorlib.dll but was not handled in user code. Additional information: Access to the path ‘\networkshare\filename.ext’ is denied.”

Root Cause

In my case, the code that was trying to open the file was calling File.OpenRead:

FileStream fileStream = File.OpenRead(fileToUpload);

File.OpenRead tries to open a file with that name in the local machine (Reference). Most of the time, the files are in the server, not in the local (client) machines. Therefore, it fails no matter what permissions are assigned to the folder.

Solution for System.UnauthorizedAccessException error

Use InputStream instead of File.OpenRead. InputStream will ensure to use the file on the server side.

String fileToUpload = FileUpload2.PostedFile.FileName;
long contentLength = FileUpload2.PostedFile.InputStream.Length;

byte[] buffer = new byte[contentLength];

FileUpload2.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);
FileUpload2.PostedFile.InputStream.Read(buffer, 0, Convert.ToInt32(contentLength));

Stream stream = new MemoryStream(buffer);

You can save the content of stream to SharePoint. Once you need to convert it back to a text, you can decode it:

string str = System.Text.Encoding.ASCII.GetString(buffer);

Looking for sample code to create and work with Office documents? Check this post out: Creating PDF, Word, Excel, Outlook and Text files using C#

Leave a Comment