geekdu972
geekdu972

Reputation: 199

Adding a string to an existing text file located on a FTP Server

I want to add this to my code:

$path="ftp://localhost/file1.txt"
$y="yes"
ADD-content -path $path -value  $a   

What is the good method please? We suppose that $LocalFile doesn't exist. I want just to add a value $y="yes" to my remote ftp file $RemoteFile file1.txt

# Config
$Username = "username"
$Password = "password"
$LocalFile = "C:\test100\log1.txt"
$RemoteFile = "ftp://localhost/file1.txt"
 
# Create FTP Rquest Object
$FTPRequest = [System.Net.FtpWebRequest]::Create("$RemoteFile")
$FTPRequest = [System.Net.FtpWebRequest]$FTPRequest
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$FTPRequest.Credentials = new-object System.Net.NetworkCredential($Username, $Password)
$FTPRequest.UseBinary = $true
$FTPRequest.UsePassive = $true
# Read the File for Upload
$FileContent = [System.IO.File]::ReadAllBytes($LocalFile)
$FTPRequest.ContentLength = $FileContent.Length
# Get Stream Request by bytes
$Run = $FTPRequest.GetRequestStream()
$Run.Write($FileContent, 0, $FileContent.Length)
# Cleanup
$Run.Close()
$Run.Dispose()

Upvotes: 0

Views: 227

Answers (1)

user15242289
user15242289

Reputation:

You want to "update" a file content located on a FTP server using another file content located on your local disk.

Try this :

# Your Local File
$File = "C:/log.txt"

# Your FTP Server location
$FTP = "ftp://root:root@localhost/test.txt"

# Create a Web Client
$Web_Client   = New-Object System.Net.WebClient

# Set file URI from your FTP Server
$URI          = New-Object System.Uri($FTP)

# Get Local File Content
$File_Content = Get-Content $File

# Download content of the file
$New_Content  = $Web_Client.DownloadString($URI)

# Add Local File Content to the downloaded content previously
$New_Content  = $New_Content + $File_Content

# Upload the Whole Content (Old + New Line)
$Web_Client.UploadString($URI,$New_Content)

# Free the Web  Client
$Web_Client.Dispose()

Upvotes: 1

Related Questions