Download file from ftp if newer or different - vb.net

I am trying to download a file from an ftp site only if it's newer than my local file. Can anyone help how to incorporate to check for the file properties? right now it downloads the file, but just need if newer. The purpose is to update a .mdb with the contents of the file, so don't want to download file and run an update everytime my app runs, only if the file is different. This is the code I am using:
Const localFile As String = "C:\version.xml"
Const remoteFile As String = "/version.xml"
Const host As String = "ftp://1.1.1.1"
Const username As String = "user"
Const password As String = "pwd"
Dim URI As String = host & remoteFile
Dim ftp As System.Net.FtpWebRequest = _
CType(FtpWebRequest.Create(URI), FtpWebRequest)
ftp.Credentials = New _
System.Net.NetworkCredential(username, password)
ftp.KeepAlive = False
ftp.UseBinary = True
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Using response As System.Net.FtpWebResponse = _
CType(ftp.GetResponse, System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using
Any help is appreciated

Not sure if this answers your question but I am looking for a similar answer and came across this.
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx
Look into LastWriteTime and you could save that time and check to see if it is a newer date then what is saved. You would have to also figure out how to download the file as a while(not familiar with the code maybe you are).

Related

VB.NET to download latest file name with timestamp in its name from FTP server

I want to pull a file from my FTP server into my local drive. However the most difficult part of do this is that the file name is a timestamp that changes on a daily basis. The program should download the file regardless of how it has changed with the date; year, month, hour, minutes, and seconds. The format of the name are always the same. File name example is below in bold. Please advise!
For example,
username - meUser
password - mepswrd
and the URL to the FTP
/afea/euser/aefe/aole/efa/
and the path I want the file to save after download it.
C:\Users\alae\Desktop\loaef
and the file is in FORMAT
20160223.171234.BA_DESRP_20160121.txt
The only part to the file that doesn't change is BA_DESRP, all the other part can change as it is a timestamp.
This is my code to start with:
Const lf As String = "C:\Users\alae\Desktop\loaef"
Const rf As String = "/afea/euser/aefe/aole/efa/"
Const ht As String = "host"
Const un As String = "username"
Const pw As String = "password"
Dim URI As String = ht & rf
Dim ftp As System.Net.FtpWebRequest = _
CType(FtpWebRequest.Create(URI), FtpWebRequest)
ftp.Credentials = New _
System.Net.NetworkCredential(un, pw)
There's no easy way with the FtpWebRequest (or any other functionality readily available in the .NET framework). You have to:
List the remote directory using the WebRequestMethods.Ftp.ListDirectory
Filter the returned list to those containing the BA_DESRP
Select the latest out of those
And download it
Dim url As String = "ftp://ftp.example.com/remote/path/"
Dim credentials As NetworkCredential = New NetworkCredential("username", "password")
Const localPath = "C:\local\path"
Dim listRequest As FtpWebRequest = WebRequest.Create(url)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
listRequest.Credentials = credentials
Dim latest As String = Nothing
Using listResponse As FtpWebResponse = listRequest.GetResponse(),
listStream As Stream = listResponse.GetResponseStream(),
listReader As StreamReader = New StreamReader(listStream)
While Not listReader.EndOfStream
Dim filename As String = listReader.ReadLine()
If filename.Contains("BA_DESRP") Then
Console.WriteLine("Found {0} ...", filename)
If (latest Is Nothing) OrElse (latest < filename) Then
latest = filename
End If
End If
End While
End Using
If Not latest Is Nothing Then
Console.WriteLine("Downloading {0} ...", latest)
Dim webClient As New WebClient()
webClient.Credentials = credentials
webClient.DownloadFile(url + latest, Path.Combine(localPath, latest))
End If
Or use another FTP library with more powerful functionality.
For example with WinSCP .NET assembly:
Const localPath = "C:\local\path\"
Const remotePath = "/remote/path"
Dim sessionOptions As New SessionOptions
With sessionOptions
.Protocol = Protocol.Ftp
.HostName = "ftp.example"
.UserName = "username"
.Password = "password"
End With
Using session As New Session
session.Open(sessionOptions)
Dim latest As RemoteFileInfo =
session.ListDirectory(remotePath).Files.
Where(Function(file) file.Name.Contains("BA_DESRP")).
OrderByDescending(Function(file) file.Name).
FirstOrDefault()
If Not latest Is Nothing Then
Console.WriteLine("Downloading {0} ...", latest)
session.GetFiles(latest.FullName, localPath).Check()
End If
End Using
If you can use the actual file timestamp (not the timestamp in its name), it would be even more straightforward. See Downloading the most recent file.
(I'm the author of WinSCP)
This will get you the list of files in the directory. Since your file name already includes the timestamp, you just need to parse it out from the file name, and then ultimately store each timestamp in a variable where you can then compare the next file's time stamp to. if next file is greater than the value you in your variable, assign that value. finally when you are done, your var should reflect the file name you need and at that stage you can call the download method to get the file.
Dim request As FtpWebRequest = WebRequest.Create("ftp://" & "servername" & "/" & "directory" & "/*")
request.Method = WebRequestMethods.Ftp.ListDirectory
request.Credentials = New NetworkCredential("username", "password")
Using reader As New StreamReader(request.GetResponse().GetResponseStream())
Do Until reader.EndOfStream
Console.WriteLine(reader.ReadLine())
Loop
End Using
since you say thousands for files, this route may not be the best option for you. if you are not restricted to .NET, you may want to explore alternative options, such as using a ftp client where you may be able to search by the actual time stamp on files...

FTP Plain Text File To Specific Directory

I am taking over a process that is completely done by hand and trying to automate it. One step is to FTP a plain text file to a specific directory on an FTP server. Everything I see when I search is dropping the file on the server not putting it in a specific directory. The error I get is file name not allowed, except it is the same name that is manually FTP'ed. Below is what code I have. What am I missing?
LocalFile = Path.GetFileName(TheFile)
URI = TheHost & RemoteDir & LocalFile
TheFtpClient = CType(FtpWebRequest.Create(URI), FtpWebRequest)
TheFtpClient.Credentials = New NetworkCredential(UserName, PassWord)
TheFtpClient.KeepAlive = False
TheFtpClient.Method = WebRequestMethods.Ftp.UploadFile
FileReader = New StreamReader(TheFile)
FileContents = Encoding.UTF8.GetBytes(FileReader.ReadToEnd())
FileReader.Close()
TheFtpClient.ContentLength = FileContents.Length
RequestStream = TheFtpClient.GetRequestStream()
RequestStream.Write(FileContents, 0, FileContents.Length)
RequestStream.Close()
TheResponse = CType(TheFtpClient.GetResponse(), FtpWebResponse)
Console.WriteLine("[" & TheResponse.StatusDescription & "]")

How to replace a file that uploading a new file to ftp server using VB.NET

Dim MkFile As System.Net.FtpWebRequest = _
DirectCast(System.Net.WebRequest.Create(FtppathBase & SavePath), System.Net.FtpWebRequest)
MkFile.Credentials = New System.Net.NetworkCredential("username", "password")
MkFile.Method = System.Net.WebRequestMethods.Ftp.UploadFile
MkFile.Timeout = 10000000
MkFile.ReadWriteTimeout = 10000000
MkFile.KeepAlive = True
Dim bFile() As Byte = System.IO.File.ReadAllBytes(FileRcrs)
Dim UpStream As System.IO.Stream = MkFile.GetRequestStream()
UpStream.Write(bFile, 0, bFile.Length)
UpStream.Close()
UpStream.Dispose()
im using this method . but its not overwrite the file . please help me to overwrite a file
You could delete the file if it exists prior to uploading the new one.
It's not the cleanest answer but its easy and should work.

Save MP3 file from URL in VB.NET

I'm attempting to download an .mp3 file from my server, and save it locally, in VB.NET. However, when I do so, the saved file is corrupt, as the contents contain multiple lines of things like below, with a ton of random/weird characters below them (I'm assuming the building blocks of the audio file).
Here's what I am seeing: http://i.troll.ws/11d37d00.png
date = "20130811_18:22:58.466";
host = "DC3APS421";
kbps = "48";
khz = "22050";
When I attempt to play the .mp3 file in WMP, it also says it's corrupt. This is the code I'm using to download and save it.
' Download the MP3 file contents
Dim request As WebRequest = WebRequest.Create("http://www.mysite.org/secure/speech/?text=Test.")
request.Credentials = CredentialCache.DefaultCredentials
Dim response As WebResponse = request.GetResponse()
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
Debug.Print("Downloaded. Saving to local Audio Cache...")
' Check and create the audio-cache directory
If (Not System.IO.Directory.Exists(WorkingDir + "\audio-cache\")) Then
Debug.Print("Audio cache directory doesn't exist. Creating... ")
System.IO.Directory.CreateDirectory(WorkingDir + "\audio-cache\")
Debug.Print("Created at " + WorkingDir + "\audio-cache\")
End If
Dim Data As String = responseFromServer
' Save the mp3 file!
Dim fileLoc As String = WorkingDir + "\audio-cache\" + Mp3Hash + ".mp3"
Dim fs As FileStream = Nothing
If (Not File.Exists(fileLoc)) Then
fs = File.Create(fileLoc)
Using fs
End Using
End If
If File.Exists(fileLoc) Then
Using sw As StreamWriter = New StreamWriter(fileLoc)
sw.Write(Data)
End Using
End If
Debug.Print("Saved successfully to " + fileLoc)
How can I properly download, and locally save, an mp3 file from a URL?
try this
Dim HttpReq As HttpWebRequest = DirectCast(WebRequest.Create("http://...."), HttpWebRequest)
Using HttpResponse As HttpWebResponse = DirectCast(HttpReq.GetResponse(), HttpWebResponse)
Using Reader As New BinaryReader(HttpResponse.GetResponseStream())
Dim RdByte As Byte() = Reader.ReadBytes(1 * 1024 * 1024 * 10)
Using FStream As New FileStream("FileName.extension", FileMode.Create)
FStream.Write(RdByte, 0, RdByte.Length)
End Using
End Using
End Using

Creating a file on my website using VB.net

I have searched but couldn't get any real solution to creating a file on my website by uploading the file from the local system using VB.net
This is my code so far
Dim rdr As New FileStream(ReSaveFile, FileMode.Open)
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://www.timemedian.com/display.txt"), HttpWebRequest)
req.Method = "POST"
' you might use "POST"
req.ContentLength = rdr.Length
req.AllowWriteStreamBuffering = True
Dim reqStream As Stream = req.GetRequestStream()
Dim inData As Byte() = New Byte(rdr.Length - 1) {}
' Get data from upload file to inData
Dim bytesRead As Integer = rdr.Read(inData, 0, rdr.Length)
' put data into request stream
reqStream.Write(inData, 0, rdr.Length)
rdr.Close()
req.GetResponse()
' after uploading close stream
reqStream.Close()
but I cant possible see the error. Please help
I uploaded the file using ftp protocol like this
Try
Dim mReq1 As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://ftp.websitename.com//" & SetID & ".pvx"), System.Net.FtpWebRequest)
mReq1.Credentials = New System.Net.NetworkCredential("username", "password")
mReq1.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim MFile1() As Byte = System.IO.File.ReadAllBytes(ReSaveFile)
Dim mStream1 As System.IO.Stream = mReq1.GetRequestStream()
mStream1.Write(MFile1, 0, MFile1.Length)
mStream1.Close()
mStream1.Dispose()
Catch ex As Exception
MsgBox("Your file was not fully posted to the remote server. PVX Mail may not function properly")
Exit Sub
End Try