PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 1, 2022

[FIXED] How to count files in FTP directory

 August 01, 2022     ftp, ftpwebrequest, powershell, string-split     No comments   

Issue

I have this script. I'm trying to count how many file are in.

clear
$ftp_uri = "ftp://ftp.domain.net:"
$user = "username"
$pass = "password"
$subfolder = "/test/out/"
$ftp_urix = $ftp_uri + $subfolder
$uri=[system.URI] $ftp_urix

$ftp=[system.net.ftpwebrequest]::Create($uri)

$ftp.Credentials=New-Object System.Net.NetworkCredential($user,$pass)

#Get a list of files in the current directory.
$ftp.Method=[system.net.WebRequestMethods+ftp]::ListDirectorydetails
$ftp.UseBinary = $true
$ftp.KeepAlive = $false
$ftp.EnableSsl = $true
$ftp.Timeout = 30000
$ftp.UsePassive=$true

try
{
 $ftpresponse=$ftp.GetResponse()
 $strm=$ftpresponse.GetResponseStream()
 $ftpreader=New-Object System.IO.StreamReader($strm,'UTF-8')
 $list=$ftpreader.ReadToEnd()

 $lines=$list.Split("`n")

 $lines
 $lines.Count

 $ftpReader.Close() 
 $ftpresponse.Close()
}
catch{
 $_|fl * -Force
 $ftpReader.Close() 
 $ftpresponse.Close()
}

In the directory I have three files but $lines.count return 4. $lines have 4 rows, three files and an empty line. Somebody can explain me the mystery?


Solution

The $list contains:

file1`nfile2`nfile3`n

If you split the string by "`n", you (correctly) get four parts, with the last one being empty.

You can use an overload of String.Split that takes StringSplitOptions and use RemoveEmptyEntries:

$list.Split("`n", [System.StringSplitOptions]::RemoveEmptyEntries)


Answered By - Martin Prikryl
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing