none
Topshelf : Windows service error RRS feed

  • Question

  • Hi Experts, 

    I have the following Topshelf code which works rarely and most of the time it errors out. Could you please support as am new to C#.

    Could you please support with fix, what exactly is going wrong with it. Even if I try to put a single file it creates the same error.

    --ConverterService.CS
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace FileConverterService
    {
        class ConverterService
        {
            private FileSystemWatcher _watcher;
            private static readonly string InProgressDirectoryName = "processing";
    
            public bool Start()
            {
                _watcher = new FileSystemWatcher(@"C:\psdata\psdata\in", "*.txt*");
    
                _watcher.Created += FileCreated;
    
                _watcher.IncludeSubdirectories = false;
    
                _watcher.EnableRaisingEvents = true;
                _watcher.InternalBufferSize = 32768; // 32 KB
    
    
                return true;
            }
    
            private void FileCreated(object sender, FileSystemEventArgs e)
            {
    
    
                string rootDirectoryPath = new DirectoryInfo(e.FullPath).Parent.Parent.FullName;
                string inputFileName = Path.GetFileName(e.FullPath);
                string inProgressFilePath =
                  Path.Combine(rootDirectoryPath, InProgressDirectoryName, inputFileName);
    
                File.Move(e.FullPath, inProgressFilePath);
    
            }
    
            public bool Stop()
            {
                _watcher.Dispose();
    
                return true;
            }
        }
    }
    
    -- Program.Cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Topshelf;
    
    namespace FileConverterService
    {
        class Program
        {
            static void Main(string[] args)
            {
                HostFactory.Run(serviceConfig =>
                                {
                                    serviceConfig.Service<ConverterService>(serviceInstance =>
                                                {
                                                    serviceInstance.ConstructUsing(
                                                        () => new ConverterService());
    
                                                    serviceInstance.WhenStarted(
                                                        execute => execute.Start());
    
                                                    serviceInstance.WhenStopped(
                                                        execute => execute.Stop());
                                                });
    
                                    serviceConfig.SetServiceName("FileMove");
                                    serviceConfig.SetDisplayName("File Mover");
                                    serviceConfig.SetDescription("File Mover Service");
    
                                    serviceConfig.StartAutomatically();
                                });
            }
        }
    }
    ---------------------------------------
    Error
    Topshelf.Hosts.ConsoleRunHost Critical: 0 : The service threw an unhandled exception, System.IO.IOException: The process cannot access the file because it is being used by another process.
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.__Error.WinIOError()
       at System.IO.File.InternalMove(String sourceFileName, String destFileName, Boolean checkHost)
       at System.IO.File.Move(String sourceFileName, String destFileName)
       at FileConverterService.ConverterService.FileCreated(Object sender, FileSystemEventArgs e) in C:\psdata\TestingLocally\FileConverterService\ConverterService.cs:line 39
       at System.IO.FileSystemWatcher.OnCreated(FileSystemEventArgs e)
       at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32 action, String name)
       at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer)
       at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
    Stopping the  service
    Control+C detected, attempting to stop service.

    • Edited by Priya Bange Sunday, November 17, 2019 12:59 PM ..
    Sunday, November 17, 2019 12:42 PM

Answers

  • Hi Priya Bange, 

    Thank you for posting here.

    According to your question, I make a test on my side and reproduce your problem.

    The exception is created by 'File.Move()' method.

    Try to use the following code.

            private const int NumberOfRetries = 3;
            private const int DelayOnRetry = 1000;
            private void FileCreated(object sender, FileSystemEventArgs e)
            {
                string rootDirectoryPath = new DirectoryInfo(e.FullPath).Parent.Parent.FullName;
                string inputFileName = Path.GetFileName(e.FullPath);
                string inProgressFilePath =
                  Path.Combine(rootDirectoryPath, InProgressDirectoryName, inputFileName);
                for (int i = 1; i <= NumberOfRetries; ++i)
                {
                    try
                    {
                        File.Move(e.FullPath, inProgressFilePath);
                        break;
                    }
                    catch (IOException) when (i <= NumberOfRetries)
                    {
                        Thread.Sleep(DelayOnRetry);
                    }
                }
            }

    Hope it can help you.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Priya Bange Monday, November 18, 2019 11:00 AM
    Monday, November 18, 2019 10:00 AM
    Moderator

All replies

  • Hello,

    Is the error on this line?

    File.WriteAllText(convertedPath, upperContent);

    As that line appears to be the only line performing write operations. 

    What code is using C:\psdata\psdata\in\data1.txt ?

    Also note TopShelf is not Microsoft plus the error is in your code logic.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, November 17, 2019 12:53 PM
    Moderator
  • Hello,

    Is the error on this line?

    File.WriteAllText(convertedPath, upperContent);

    As that line appears to be the only line performing write operations. 

    What code is using C:\psdata\psdata\in\data1.txt ?

    Also note TopShelf is not Microsoft plus the error is in your code logic.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Hello, 

    I have just updated the code. Please refer to most recent error received. Updated the above shared details. 

    Thanks 

    Sunday, November 17, 2019 12:56 PM
  • Hello, 

    Am trying now to move the file and got similar issue. The data1.txt contains some words like Hello World".

    I had restarted my machine in case some background process didn't cleanly exited but still even on a fresh restart got the same error while trying to copy the file. Please support 

    Thanks

    Priya

    Sunday, November 17, 2019 1:01 PM
  • Hi Experts,

    Any leads for this error 

    System.IO.IOException: 
    The process cannot access the file because it is being used by another process.

    from the above code... 

    Thanks 

    Priya

    Monday, November 18, 2019 6:59 AM
  • Hi Priya Bange, 

    Thank you for posting here.

    According to your question, I make a test on my side and reproduce your problem.

    The exception is created by 'File.Move()' method.

    Try to use the following code.

            private const int NumberOfRetries = 3;
            private const int DelayOnRetry = 1000;
            private void FileCreated(object sender, FileSystemEventArgs e)
            {
                string rootDirectoryPath = new DirectoryInfo(e.FullPath).Parent.Parent.FullName;
                string inputFileName = Path.GetFileName(e.FullPath);
                string inProgressFilePath =
                  Path.Combine(rootDirectoryPath, InProgressDirectoryName, inputFileName);
                for (int i = 1; i <= NumberOfRetries; ++i)
                {
                    try
                    {
                        File.Move(e.FullPath, inProgressFilePath);
                        break;
                    }
                    catch (IOException) when (i <= NumberOfRetries)
                    {
                        Thread.Sleep(DelayOnRetry);
                    }
                }
            }

    Hope it can help you.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Priya Bange Monday, November 18, 2019 11:00 AM
    Monday, November 18, 2019 10:00 AM
    Moderator