Search code examples
c#windows-serviceslockingxmldocumentstreamreader

File is being locked when I try to execute delete


I have a service that reads an xml document from a directory(works OK), saves the data in sql (works OK) and after that I am copying the file to a FINISHED directory (works OK) and deleting the file (NOT working)from the reading directory. The PROBLEM that I have is that the file is being locked when I try to execute the DELETE. Any advise will be appreciated so I can find where the file is being locked.

static public Res GetResMn(string FileName)             
XDocument root = null;
using (var file = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (StreamReader oReader = new StreamReader(file, Encoding.GetEncoding("ISO-8859-1")))
            {
                root = XDocument.Load(oReader);
                oReader.Close();
                oReader.Dispose();
            }

Here is the code for the copy and delete

    void CopyFile(string FileToMove, string MoveLocation)
    {
        try
        {
             System.IO.File.Copy(FileToMove, MoveLocation, true);
            //System.IO.File.Move(FileToMove, MoveLocation);

                File.Delete(FileToMove);
        }
        catch (Exception e)
        {
            WriteLogFile("The process failed: {0} " + e.ToString());
        }
    }

This is the code when I get the values from the file

    var myElement1 = root.Descendants(XName.Get("rnID", @"namespace.2.0")).FirstOrDefault();
    if (myElement1 != null)
    {
        myRPr.rnID = root.Descendants(XName.Get("rnID", @"namespace.2.0")).FirstOrDefault().Value;
    }

This is the error that I am getting in my logFile

{0} System.UnauthorizedAccessException: Access to the path 'C:\ReadingDirectory\FileName.xml' is denied.
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path)
    at OperaWinSrvc.OperaWinSrvc.ReadFiles()

I am gettign the same kind of error when I tried the System.IO.File.Move


Solution

  • After doing multiple check ups in different places I finally found the solution to my problem. In the service installer I had the Account property set to Local Service, I change it to LocalSystem, reinstall the service and it appears to work now.