【发布时间】:2020-10-26 16:53:32
【问题描述】:
我们有来自第三方编码的 UTF-16 LE 的订单。我们的 ERP 只能读取 UTF-8 编码。因此,我创建了 .NET Core 控制台应用程序,用于监视订单到达的目录并将它们写入 ERP 抓取文件的位置。如何让它在我们的 Windows Server 2016 上运行?我应该废弃它并将其编写为 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();
}
}
}
我看过一些类似的帖子,但不确定我应该采取什么方向。任何方向将不胜感激!
【问题讨论】:
-
您可以将其重写为一项服务——这具有一定的优势——但最少的工作是将其保留为控制台应用程序,只需使用Windows task scheduler 安排它偶尔运行。
标签: c# .net-core windows-server