asp.net-corefilestreamassembliesimpersonation

How to let my code access assembly while impersonating


I'm trying to read images on a shared folder using WindowsIdentity.RunImpersonated. The problem is that during impersonation, my code can't access the System.Drawing.Common assembly, probably because the impersonated user has no access on it, what can I do.

WindowsIdentity.RunImpersonated(safeAccessTokenHandle,() => {
            string[] files = Directory.GetFiles(path, pattern);

            if (files.Length > 0)
            {
                foreach (string file in files)
                {
                    string[] f = file.Split('.');
                    FileStream fstream = new FileStream(file, FileMode.Open);
                    Bitmap bitmap = new Bitmap(fstream);
                    MemoryStream ms = new MemoryStream();
                    bitmap.Save(ms, ImageFormat.Jpeg);
                    byte[] byteImage = ms.ToArray();
                    model.Archive.Add(Convert.ToBase64String(byteImage));
                    fstream.Close();
                }
            }
        });

This is the error I get :

FileLoadException: Could not load file or assembly 'System.Drawing.Common, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. Access is denied.


Solution

  • This worked for me case anyone faced this problem Add this line of code before WindowsIdentity.RunImpersonated

    Assembly.Load("System.Drawing.Common, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");