Search code examples
c#sitecoresitecore7

Sitecore deleting a file from the server with Schedule Tasks


In the schedule tasks in Sitecore I want to delete an XML file after data import. Data import is successful but when deleting I get the access denied exception.

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
System.UnauthorizedAccessException: Access to the path 'X:\..\Website\temp\import\data.xml' is denied. at 
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at
System.IO.File.InternalDelete(String path, Boolean checkHost) at Website.Intranet.Kernel.ScheduledTasks.Scheduler.ImportData()

This is the code I am using to delete the file.

if (File.Exists(filePath))
            {
                File.SetAttributes(filePath, FileAttributes.Normal);
                File.Delete(filePath);

            }

Solution

  • Make sure you grant the correct permissions on your target folder for the Application Pool identity user on which your website is running. By default the identity is Application Pool Identity or NetworkService.

    Also make sure the containing folder is not readonly