Search code examples
c#asp.netsilverlight

Error: File operation not allowed. Access to route denied


I am working on a project that uses Silverlight, where I want to show PDFS files of a server path, but when I start debugging my code I find the following exception:

enter image description here

where I generate the flow in the following code:

System.Windows.Browser.HtmlElement myFrame = System.Windows.Browser.HtmlPage.Document.GetElementById("_sl_historyFrame");
            if (myFrame != null)
            {
                DirectoryInfo folderPath = new DirectoryInfo(@"\\192.168.1.216\UploadFileMobilePDF\" + transfer.IdTransfer);
                foreach (var file in folderPath.EnumerateFiles("*.pdf", SearchOption.AllDirectories))
                {
                    myFrame.SetStyleAttribute("width", "1024");
                    myFrame.SetStyleAttribute("height", "768");
                    Uri uri = new Uri(folderPath + file.FullName);
                    string path = uri.AbsoluteUri.ToString();
                    myFrame.SetAttribute("src", path);
                    myFrame.SetStyleAttribute("left", "0");
                    myFrame.SetStyleAttribute("top", "50");
                    myFrame.SetStyleAttribute("visibility", "visible");
                }
            }

The error marks me when instantiating the DirectoryInfo class folderPath = new DirectoryInfo ()

I don't know if silverlight can't have permissions to server addresses


Solution

  • Your application likely doesn't have permission to access the files on the server you're trying to access.

    Look into WindowsImpersonationContext for the most likely way around this. https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsimpersonationcontext?view=netframework-4.8

    You'll want a class (say, "MyImpersonator") that uses WindowsImpersonationContext to log onto the server using valid credentials. There are too many details to present an entire solution, but using the class (defined elsewhere) to get a single file might look something like this:

         using (var impersonator = new MyImpersonator())
         {
            string name = ConfigurationManager.AppSettings["name"];
            string password = ConfigurationManager.AppSettings["pass"];
    
    
            if (impersonator.LogOnCrossDomain(account, pass))
            {                   
                 if (File.Exists(filepath))
                 {                           
                     byte[] content = File.ReadAllBytes(filepath);                          
                 }
             }  
          }