Published Aug 01 2019 11:37 AM 3,151 Views

If the file you are trying to access is not available or you don’t have permissions to access it, your web application (or SharePoint web part in my case) may throw System.UnauthorizedAccessException error. Full error message:


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 the case I worked on, the code line that was trying to open the file was using File.OpenRead:



FileStream fileStream = File.OpenRead(fileToUpload);



File.OpenRead tries to open a file with the name in the local machine, not in the server. The file is most likely in the server, not in the local (client) machines. Therefore, it throws an error even if you assigned perrmissions to the folder.




Use InputStream instead of File.OpenRead. InputStream will make sure 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);



If you want to save the content of stream to SharePoint, you can decode it by using the method below:



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





Version history
Last update:
‎Aug 01 2019 11:38 AM
Updated by: