windowspowershellftpftpwebrequestgetresponsestream

Powershell: GetRequestStream


I try to upload file from local computer to ftp server. And i've got the error below:

Exception calling "GetRequestStream" with "0" argument(s): "The process cannot access the file 'Path_to_File' because it is being used by another process."
At line:1 char:1
+ $ftpRequestStream = $ftpRequest.GetRequestStream()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

It is the my code:

$usr = "admin"
$pass = "admin"
$ftp="ftp://$RouterIP"
$subfolder='/'
$FileName = "def.backup"
$DirTarget = "C:\MyOwn\Scritps"
$ftpuri = $ftp + $subfolder + $FileName
$SourceFile = "$DirTarget\$FileName"
$AuthRequest = "ftp://"+$usr + ":" + $pass + "@$RouterIP" + "/$FileName"


function UploadFile ($SourceUri,$UserName,$Password){

$fileToUpload = $SourceUri
$ftpRequest = [System.Net.FtpWebRequest]::Create($fileToUpload)
$ftpRequest.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)
$ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$fileStream = [System.IO.File]::OpenRead($fileToUpload)
$ftpRequestStream = $ftpRequest.GetRequestStream()
$fileStream.CopyTo($ftpRequestStream)
$fileStream.Close()
$ftpRequestStream.Close()

}

UploadFile -SourceUri $SourceFile -UserName $usr -Password $pass

}

At the same time, the system shows that this file is held by the powershell_ise process and no one else. Obviously, it is also not open anywhere or by anyone. What's wrong? Where's the plug?


Solution

  • Your UploadFile method is missing the destination/ftp parameter and so you are mixing up your paths. In fact you are using your source file as source and as destination. So add another parameter to pass your ftp path and use that for [System.Net.FtpWebRequest]::Create

    $usr = "admin"
    $pass = "admin"
    $ftp="ftp://$RouterIP"
    $subfolder='/'
    $FileName = "def.backup"
    $DirTarget = "C:\MyOwn\Scritps"
    $ftpuri = $ftp + $subfolder + $FileName
    $SourceFile = "$DirTarget\$FileName"
    $AuthRequest = "ftp://"+$usr + ":" + $pass + "@$RouterIP" + "/$FileName"
    
    function UploadFile ($SourceUri, $Destination, $UserName, $Password){
    
    $ftpRequest = [System.Net.FtpWebRequest]::Create($Destination)
    $ftpRequest.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)
    $ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
    $fileStream = [System.IO.File]::OpenRead($SourceUri)
    $ftpRequestStream = $ftpRequest.GetRequestStream()
    $fileStream.CopyTo($ftpRequestStream)
    $fileStream.Close()
    $ftpRequestStream.Close()
    
    }
    
    UploadFile -SourceUri $SourceFile -Destination $ftpuri -UserName $usr -Password $pass
    

    BTW: The naming of your variables is kind of weird. You use $DirTarget to create $SourceFile? Why not name it $SourceDir?