Search code examples
c#asp.netfileasp.net-web-apiio

UnauthorizedAccessException on reading file


I have and ASP Web API and I'm trying to return a file from a call there.

On my server I keep getting the error:

System.UnauthorizedAccessException: Access to the path 'E:\Data\Docs\specific\document.pdf' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at GIS.Backend.Assets.BLL.Document.GetByUrl(String url) at GIS.Backend.Assets.WebApi.Controllers.DocumentController.Get(String url)

I'm guessing this is where it goes wrong:

string documentenPath = System.Web.Configuration.WebConfigurationManager.AppSettings["DocumentenDir"].ToString();
        string fullUrl = documentenPath + url;

        Stream file = new FileStream(fullUrl, FileMode.Open);
        return file;

I have set IIS_IUSRS to have read access to the 'Docs' folder, so it should be able to read right?


Solution

  • open the Stream with the FileAccess.Read flag

    FileStream fs = new FileStream(fullUrl, FileMode.Open, FileAccess.Read);