Fix System.UnauthorizedAccessException with C# code for SharePoint on premise service
I developed a service for SharePoint 2019 (on premise) and this service should move files from document library to an external storage. The client part is made with SPFX solution – command set. It added buttons to the interface of the document library.
What about backend, for the start of the development I wanted to move user files to a folder of my developer server. And I immediately started to get errors like this:
System.UnauthorizedAccessException: 'Access to the path '\\DeveloperPC\ArchiveDir\1235.docx' is denied.'
The sample of the code is this one:
string workdir = @"\\DeveloperPC\ArchiveDir"; string myFile = Path.Combine(workdir, listItemId + ".docx"); FileStream f = new FileStream(myFile, FileMode.Open); int length = (int)f.Length;
To fix this problem you should disable ASP.Net impersonation.
ASP.Net impersonation is a Windows feature that allows to transfer user from IIS to other services. To tell the truth, I don't like it. With services I prefer to work with technical account and to implement the logic with code.