代码之家  ›  专栏  ›  技术社区  ›  Karthikeyan

使用FtpWebRequest从远程服务器下载的文件内容显示在记事本的一行中

  •  1
  • Karthikeyan  · 技术社区  · 7 年前

    我正在从远程服务器复制文件,并使用PowerShell保存在本地计算机中。但当我在记事本中打开该文件时,从远程服务器复制了该文件后,它并没有以正确的格式打开(对齐)。但如果我使用FTP命令手动复制,它在记事本中的对齐方式是正确的。

    请查找我的PowerShell脚本:

    $File = "D:\copiedfile.txt"
    $ftp = "ftp://remote_machine_name//tmp/text.txt"
    $ftprequest = [System.Net.FtpWebRequest]::Create($ftp)
    $ftprequest.UseBinary = $true
    
    "ftp url: $ftp"
    $webclient = New-Object System.Net.WebClient
    $uri = New-Object System.Uri($ftp)
    "Downloading $File..."
    $webclient.DownloadFile($uri, $File)
    

    请在使用PowerShell脚本(未正确对齐)复制文件后查找随附的屏幕截图。

    enter image description here

    请在使用FTP手动复制文件(正确对齐)后查找所附的屏幕截图。

    enter image description here

    由于跨平台,我遇到了这个对齐问题。正在将文件从HP-UX复制到Windows。不知道如何解决这个问题。

    当am通过FTP手动(命令行)复制文件时,其传输模式为ASCII。但我不确定如何在powershell脚本中设置ASCII的传输模式。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Martin Prikryl    6 年前

    Windows记事本仅支持Windows EOL 。您的文件很可能具有*nix EOL。

    您需要使用ascii/文本模式,而不是二进制模式,以便 FtpWebRequest 可以将文件转换为Windows EOL。

    $ftprequest.UseBinary = $False
    

    但是请注意,当您创建 FtpWebRequest测试 ,您从未真正使用过它。

    完整代码如下所示:

    $url = "ftp://remote_machine_name//tmp/text.txt"
    $ftprequest = [System.Net.FtpWebRequest]::Create($url)
    $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
    $ftprequest.UseBinary = $false
    
    $ftpresponse = $ftprequest.GetResponse()
    $responsestream = $ftpresponse.GetResponseStream()
    
    $localPath = "D:\copiedfile.txt"
    $targetfile = New-Object IO.FileStream($localPath, [IO.FileMode]::Create)
    $responsestream.CopyTo($targetfile);
    $responsestream.Close()
    $targetfile.Close()
    

    (并移除所有 WebClient 代码)

    Stream.CopyTo 已添加到中。净额4。如果需要使用的旧版本。NET中,您需要在循环中复制流内容,如中所示 Changing FTP from binary to ascii in PowerShell script using WebClient


    它可以与命令行一起正常工作 ftp ,因为它默认为ascii/文本模式。