简体   繁体   English

将 .NET Core 控制台应用程序作为服务运行,还是重做?

[英]Running .NET Core console app as a service, or redo?

We have orders that come in from a third party encoded UTF-16 LE.我们有来自第三方编码的 UTF-16 LE 的订单。 Our ERP can only read UTF-8 encoding.我们的ERP只能读取UTF-8编码。 So I've created the .NET Core console app that watches the directories the orders arrive in and writes them to where the ERP grabs the files.所以我创建了 .NET Core 控制台应用程序,它监视订单到达的目录并将它们写入 ERP 获取文件的位置。 How do I let this run on our Windows Server 2016?如何让它在我们的 Windows Server 2016 上运行? Should I scrap it and write it as a Windows Service?我应该废弃它并将其编写为 Windows 服务吗?

using System;
using System.IO;

public class RewriteUsingUTF8
{
    public static void Main()
    {
        string ordrstkPath = @"\\Rep-app\sftp_root\supplypro\ordrstk";
        string conrstkPath = @"\\Rep-app\sftp_root\supplypro\Conrstk";
        Watch(ordrstkPath);
        Watch(conrstkPath);
        Console.ReadLine();
    }

    private static void Watch(string path)
    {
        //initialize
        FileSystemWatcher watcher = new FileSystemWatcher();

        //assign parameter path
        watcher.Path = path;

        //create event
        watcher.Created += FileSystemWatcher_Created;
        watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.Attributes;

        //only look for csv
        watcher.Filter = "*.csv";

        // Begin watching.
        watcher.EnableRaisingEvents = true;
    }

    // method when event is triggered (file is created)
    private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)

    {

        ReadWriteStream(e.FullPath, e.Name);

    }

    private static void ReadWriteStream(string path, string fileName)
    {

        FileStream originalFileStream = new FileStream(path, FileMode.Open, FileAccess.Read);

        //destination path by replacing SFTP user directory
        string destinationPath = path.Replace(@"\supplypro\", @"\ftpuser\");

        FileStream destinationFileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write);

        StreamReader streamReader = new StreamReader(originalFileStream);

        StreamWriter streamWriter = new StreamWriter(destinationFileStream);

        string currentLine;

        try
        {
            currentLine = streamReader.ReadLine();
            while (currentLine != null)
            {
                streamWriter.WriteLine(currentLine);
                currentLine = streamReader.ReadLine();
            }

            //archive path
            string archivePath = path.Replace(fileName, @"\archive\" + fileName);

            //move to archive path
            File.Move(path, archivePath);
        }
        catch (Exception e)
        {
            //error path
            string errorPath = path.Replace(fileName, @"\error\" + fileName);

            //move to error path
            File.Move(path, errorPath);

            //need to write code for error to write to event viewer
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            //dispose resources
            streamReader.Close();
            streamWriter.Close();
            originalFileStream.Close();
            destinationFileStream.Close();
        }

    }

}

I have looked at a few similar posts, but am unsure what direction I should take.我看过一些类似的帖子,但不确定我应该采取什么方向。 Any direction would be greatly appreciated!任何方向将不胜感激!

Sounds like we're working in very similar environments.听起来我们在非常相似的环境中工作。 We started off using console apps for our ERP integrations.我们开始使用控制台应用程序进行 ERP 集成。 Their main drawbacks are that they run on a user's desktop, so you have to RDP in as that user to manage them, and they don't restart automatically if the server reboots.它们的主要缺点是它们在用户的桌面上运行,因此您必须以该用户的身份进入 RDP 来管理它们,并且如果服务器重新启动它们不会自动重新启动。 I've been converting them all to Windows services.我一直在将它们全部转换为 Windows 服务。 .NET Core makes it fairly easy. .NET Core 使它变得相当容易。

Tim Corey has an excellent video about how to write Windows services in .NET Core 3 . Tim Corey 有一个关于如何在 .NET Core 3 中编写Windows 服务的优秀视频。 He talks about deleting and recreating the service when deploying a new version, but I haven't found that to be necessary.他谈到在部署新版本时删除和重新创建服务,但我认为没有必要这样做。 Just RDP in, stop the service so none of the files are in use, deploy, and start it again.只需 RDP,停止服务以便没有文件在使用中,部署并重新启动它。 It's not as simple as redeploying a .NET Core web app, which manages all the stopping and restarting for you, but it's not too bad.这不像重新部署 .NET Core Web 应用程序那么简单,它会为您管理所有停止和重新启动,但也不错。

A crucial thing to know is that exceptions absolutely must not propagate out of Worker.ExecuteAsync .需要知道的关键是异常绝对不能从Worker.ExecuteAsync传播出去。 They will not be handled anywhere, and Windows will show your service as running when it's not.它们不会在任何地方处理,Windows 会在您的服务未运行时将其显示为正在运行。 Whatever you do in ExecuteAsync , do it in a loop that catches all exceptions and keeps running.无论您在ExecuteAsync中做什么,都要在捕获所有异常并保持运行的循环中进行。

File watchers are deceptively complicated.文件观察器看似复杂。 Make sure you're listening for error events.确保您正在侦听错误事件。 For example, if you're watching a network share and it becomes unavailable, the FileSystemWatcher will emit an error and will not resume working when the share comes back online.例如,如果您正在监视网络共享并且它变得不可用,则FileSystemWatcher将发出错误并且在共享重新联机时不会恢复工作。 I haven't figured out the best way to handle errors, though.不过,我还没有想出处理错误的最佳方法。 I think making it reliable requires replacing the FileSystemWatcher after any error.我认为使其可靠需要在出现任何错误后更换FileSystemWatcher

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Linux 应用服务上的 docker 容器中运行.Net Core 控制台应用 - Running .Net Core console app in docker container on Linux App Service 在 .net 核心 3.0 BackgroundService 应用程序中,为什么我的配置 object 作为服务运行时为空,而不是作为控制台应用程序运行? - In a .net core 3.0 BackgroundService app, why is my configuration object empty when running as service, but not as console app? .Net core 2.0控制台应用程序作为Windows服务 - .Net core 2.0 console app as a windows service .Net Core 控制台应用程序未在 Docker 容器中运行 - .Net Core Console App not running in Docker container .NET Core 3.1 控制台应用作为 Windows 服务 - .NET Core 3.1 Console App as a Windows Service Net Core 2控制台应用程序-DI'无法解析类型的服务...' - Net Core 2 Console App - DI 'Unable to resolve service for type…' .NET Core DI - 在控制台应用程序中处理 Singleton 服务 - .NET Core DI - disposing of Singleton service in Console App 在.Net核心控制台应用程序中使用Azure Service Bus - Using Azure Service Bus in .Net core console app 使用肥皂网络服务的.net核心控制台应用程序出现问题 - Issue with an console app with .net core which uses a soap web service .net core 2.0错误在ubuntu上运行控制台应用程序 - .net core 2.0 error running console app on ubuntu
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM