microsoft / Dynamics-AX-Integration

Dynamics AX Integration samples and demos.
287 stars 356 forks source link

File is being picked up while still being copied by user (DIXF) #52

Open RobvanB opened 6 years ago

RobvanB commented 6 years ago

We ran into a problem where the tool would pick up a file from the input folder while the copy process had not yet completed.

I implemented the code below in the file processor class to fix this.

private void sharedFolderFileCreatedHandler(object source, FileSystemEventArgs e) { form.logText("File - " + Path.GetFileName(e.FullPath) + " - found in input location.");

        // ITK - RvB - 2017_11_23 -->
        // Prevent the file being picked up while it is still being copied by the user
        if (this.IsFileReady(e.FullPath) == true)
        {
        // ITK - RvB - 2017_11_23 <--

            Task.FromResult(this.DataNetworkStrategy.PostMessageAsync(
                new ClientDataMessage()
                {
                    Name = Path.GetFileName(e.FullPath),
                    FullPath = e.FullPath,
                    MessageStatus = MessageStatus.Input
                }));

        }   // ITK - RvB - 2017_11_23 <--
    }

    // ITK - RvB - 2017_11_23 -->
    // Make sure file is not in use
    private bool IsFileReady(String sFilename)
    {
        // If the file can be opened for exclusive access it means that the file
        // is no longer locked by another process.
        bool isReady = false;

        while (isReady == false)
        {
            System.Threading.Thread.Sleep(500);
            try
            {
                using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    if (inputStream.Length > 0)
                    {
                        isReady = true;
                    }
                    else
                    {
                        isReady = false;
                    }

                }
            }
            catch (Exception)
            {
                isReady = false;
            }
        }
        return true;
    }
    // ITK - RvB - 2017_11_23 <--