c# - 如何从 Windows 服务将文件复制到网络位置?

标签 c# windows-services

我想在 Windows Server 2008 服务器上运行一个 Windows 服务,它将监视本地服务器上的一个目录(即 C:\Watch),当在该目录中创建一个新的 pdf 时,将文件复制到网络共享(即//192.168.1.2/Share)。

两个服务器都不是域的成员。

Windows 服务将其登录设置为本地用户帐户,该帐户可以访问//server/share 并创建和删除文件,没有任何问题。

如果 sourceDir 和 destDir 是本地文件夹,如 C:\Source 和 C:\Dest,我有以下工作正常,但如果我将 destDir 更改为网络位置,如//server/share/或////server//share//我收到错误“文件名、目录名或卷标语法不正确”。

更新: 我不再收到上面的错误,现在当我将 sourceDir 设置为 C:\Watch 并将 destDir 设置为\server\share\(服务器可以是 Windows 或 Ubuntu 服务器时,我收到 System.UnauthorizedAccess 错误我假设来自目标服务器。如何设置连接到目标服务器时要使用的凭据。请记住,服务器不在域中,可以是 Windows 或 Ubuntu。

public partial class Service1 : ServiceBase
{
    private FileSystemWatcher watcher;
    private string sourceFolder;
    private string destFolder;

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        this.sourceFolder = Properties.Settings.Default.sourceDir;
        this.destFolder = Properties.Settings.Default.destDir;

        watcher = new FileSystemWatcher();
        watcher.Path = this.sourceFolder;
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.pdf";

        watcher.Created += new FileSystemEventHandler(watcher_Created);

        watcher.EnableRaisingEvents = true;
    }

    protected override void OnStop()
    {
    }

    private void watcher_Created(object source, FileSystemEventArgs e)
    {
        FileInfo fInfo = new FileInfo(e.FullPath);
        while (IsFileLocked(fInfo))
        {
            Thread.Sleep(500);
        }
        System.IO.File.Copy(e.FullPath, this.destFolder + e.Name);
        System.IO.File.Delete(e.FullPath);
    }
}

最佳答案

服务器份额为:

string networkShare = @"\\ServerName\Share\";

另请记住,服务执行的身份将影响服务是否能够保存到该位置。如果您使用域服务帐户来运行服务,请确保从共享所在的计算机调整目标共享文件夹上的 ACL 以允许写入

关于c# - 如何从 Windows 服务将文件复制到网络位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5329703/

相关文章:

windows-services - 消息队列消费者应该如何在微服务环境中模拟 Identity Server 3 中的用户?

c++ - 如果从 64 位进程安装,Windows 服务是否是 64 位的?

c++ - 在服务启动期间调用 CoCreateInstance

.net - Windows 服务将文件写入网络共享

c# - Int[].Contains 在 EF6 中不起作用

c# - 如何找到 wpf 应用程序的根路径并在根目录上创建用于保存图像的文件夹?

c# - 如何在 EXE 中存储文件

delphi - 双击Windows Service可执行文件进行配置

c# - 如何在 asp.net c# 中验证 json 字符串?

c# - 构建组合矩阵