How can download file from FTP server with some extension in VisualBasic - vb.net

I want to download the some file on remote location from FTP protocol, that have any extentions. For example I want to download the all file from remote site *.pdf, *.txt . So I have build this code in Visual Basic.
Public Function GetFiles() As Generic.List(Of String)
Dim fileList As New Generic.List(Of String)
Select Case _config.Protocol
Case FTPConfiguration.FTPProtocol.FTP
Dim objFTPRequest As FtpWebRequest = CType(FtpWebRequest.Create(New Uri(_config.FTPUrl & _config.MonitorDirectory)), FtpWebRequest)
objFTPRequest.Credentials = New NetworkCredential(_config.FTPUsername, _config.FTPPassword)
objFTPRequest.KeepAlive = False
objFTPRequest.UsePassive = False
objFTPRequest.UseBinary = True
objFTPRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim response As FtpWebResponse = CType(objFTPRequest.GetResponse(), FtpWebResponse)
Using respStream As StreamReader = New StreamReader(objFTPRequest.GetResponse().GetResponseStream())
Dim line As String = respStream.ReadLine()
While line IsNot Nothing
If line Like _config.FileSearch Then
fileList.Add(line)
End If
line = respStream.ReadLine()
End While
End Using
End Select
For Each fileName As String In fileList
Me.DownloadFile(fileName)
Next
Return fileList
End Function
How you can see, I have write this line to find the File but not works:
If line Like _config.FileSearch Then
I use LIKE operator but I think that this is not the corret way to fixed my problem.

You could use line.EndsWith(".pdf") to check if the file ends with that extension.
If you want to use like, the _config.FileSearch must be "*.pdf".
If line Like "*.pdf" Then
Console.WriteLine(line)
End If
You can also use Regular Expressions.
If Regex.IsMatch(line, "^.*\.(pdf|doc|txt|zip)$", RegexOptions.IgnoreCase) Then
Console.WriteLine(line)
End If
Refer String.EndsWith and Like

Related

VB.net: overwrite everything in a text file

in my VB.net Application id like to overwrite and add new content of a text file
What Code do I need to use?
Thanks
Read (ie: load) everything in the TXT file into your program.
Dim sFullPathToFile As String = Application.StartupPath & "\Sample.txt"
Dim sAllText As String = ""
Using xStreamReader As StreamReader = New StreamReader(sFullPathToFile)
sAllText = xStreamReader.ReadToEnd
End Using
Dim arNames As String() = Split(sAllText, vbCrLf)
'Just for fun, display the found entries in a ListBox
For iNum As Integer = 0 To UBound(arNames)
If arNames(iNum) > "" Then lstPeople.Items.Add(arNames(iNum))
Next iNum
Because you wanted to overwrite everything in the file, we now use StreamWriter (not a StreamReader like before).
'Use the True to indicate it is to be appended to existing file
'Or use False to open the file in Overwrite mode
Dim xStreamWRITER As StreamWriter = New StreamWriter(sFullPathToFile, False)
'Use the carriage return character or else each entry is on the same line
xStreamWRITER.Write("I have overwritten everything!" & vbCrLf)
xStreamWRITER.Close()

Illegal Characters in path when grabbing text from a file?

I'm getting illegal characters in path, but the directory (the path) will be different for everyone, so I'm not setting a value for the "path", it's what the user chooses in the file explorer.
I haven't seen a solution for VB.net yet so here's the code I have now:
myFileDlog.InitialDirectory = "c:\"
myFileDlog.Filter = "Txt Files (*.txt)|*.txt"
myFileDlog.FilterIndex = 2
myFileDlog.RestoreDirectory = True
If myFileDlog.ShowDialog() =
DialogResult.OK Then
If Dir(myFileDlog.FileName) <> "" Then
Else
MsgBox("File Not Found",
MsgBoxStyle.Critical)
End If
End If
'Adds the file directory to the text box
TextBox1.Text = myFileDlog.FileName
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
Dim lines() As String = IO.File.ReadAllLines(fileReader)
At Dim lines() As String = IO.File.ReadAllLines(fileReader)
It breaks with the Illegal Characters in Path exception, and I'm not sure how to test where the illegal character is, because it's grabbing from your own file directory. Any help with this?
The problem originated from this line:
Dim fileReader As String = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
fileReader takes all string contents from the corresponding file name and pass it into File.ReadAllLines method at next line, throwing ArgumentException with illegal file path message if illegal characters found inline.
Correct way to read file contents using ReadAllLines is using predefined file path or directly using FileDialog.FileName property as argument given below:
Using myFileDlog As OpenFileDialog = New OpenFileDialog()
' set dialog filters here
If (myFileDlog.ShowDialog() = DialogResult.OK) Then
If Dir(myFileDlog.FileName) <> "" Then
Dim lines() As String = File.ReadAllLines(myFileDlog.FileName)
For Each line As String In lines
' do something with file contents
Next
Else
' show "file not found" message box
End If
End If
End Using
Since ReadAllLines already being used to fetch all file contents, usage of ReadAllText may be unnecessary there.

Writing Part/Block of File to another File

Please Help: I would like to read one block from file inPath and write to another file outPath.
I am using ReadLines method to read the File line by line and when reach at START_BLOCK, start writing to the output file and continue until you find the END_BLOCK.
I know couple of other methods by copying the whole file into a variable and pick the block what I need. I can't use saving on a variable as my files are very big GB+
The coding I have below copies the line at the "START_BLOCK" Can't really figure it out how to continue writing until the "END_BLOCK". Please suggest and thank you very much in advance.
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
'-------HOW DO I CONTINUE TO WRITE UNTIL "END_BLOCK"
End If
Next line
End Using
You could just set a flag to indicate that you are inside of the block, and use that to write out the lines until you find the end tag, e.g. something like this (untested code!):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
Exit For
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
UPDATE
Since the comments are getting out of control - here's a version to handle multiple blocks with different start tags but the same end tag (untested since I'm at home on my Mac):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If IsStartOfBlock(line) Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
'...
' Logic to determine if the line is the start of a block, for example:
Private Function IsStartOfBlock(line As String) As Boolean
Dim startMarkers() As String = {
"START_BLOCK", "START_BLOCK2", "START_BLOCKX"
}
Return startMarkers.Any(Function(x) line.Contains(x))
End Function
The loop will exit at the end of file anyway, so the last block should be ok too.

Why does File.Open() not open the file?

I am implementing a Save File button in my VB.NET Windows Forms application.
I am attempting to encapsulate the normally expected behaviour of Save buttons in Windows applications. I.E: If a file was already selected then open the current file it, write to it and save it; else if there is no current file, or Save As was used, then show a SaveFileDialog, then open, write and save just the same.
I currently have coded the function below but I keep getting an exception:
Cannot access a closed file
The file is created just fine, but is empty (It should contain "Test string"). I can't understand how the file is closed unless some kind of garbage collection is doing away with it somehow??
The current code:
Function SaveFile(ByVal Type As ProfileType, ByVal suggestedFileName As String, ByVal saveAs As Boolean, ByVal writeData As String) As Boolean
Dim FileStream As Stream = Nothing
Dim FolderPath As String = Nothing
Dim CancelSave As Boolean = False
Dim SaveFileDialog As SaveFileDialog = New SaveFileDialog()
Try
If Type = ProfileType.Product Then 'Select the initial directory path
FolderPath = ProductPath
Else
FolderPath = ProfilePath
End If
If (FileName = String.Empty Or saveAs = True) Then 'If a file is not already selected launch a dialog to allow the user to select one
With SaveFileDialog
.Title = "Save"
.AddExtension = True
.CheckPathExists = True
.CreatePrompt = False
.DefaultExt = "xml"
.Filter = "Xml Files (*.xml)|*.xml"
.FilterIndex = 0
.FileName = suggestedFileName
.InitialDirectory = FolderPath
If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
FullyQualfiedPathName = New String(SaveFileDialog.FileName) 'Save the path and name of the file
FileName = Path.GetFileName(FullyQualfiedPathName)
Else
CancelSave = True
End If
.Dispose()
End With
End If
If (FileName <> String.Empty) Then 'Write the string to the file if the filewas correctly selected
FileStream = File.Open(FullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite) 'Open the file
Using FileStreamWriter As New StreamWriter(FileStream) 'Create the stream writer
FileStreamWriter.Write(writeData) 'Write the data
FileStream.Close() 'Clse the file
End Using
ElseIf (CancelSave <> True) Then 'Only throw an exception if the user *didn't* cancel the SavefileDialog
Throw New Exception("File stream was nothing", New IOException())
End If
Catch ex As Exception
MessageBox.Show(ex.Message & Environment.NewLine & FullyQualfiedPathName)
End Try
Return True
End Function
One problem I see is that you should be putting your File.Open in a Using block:
Using fs = File.Open(fullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite)
Using writer As New StreamWriter(fs) 'Create the stream writer
writer.Write(writeData) 'Write the data
'fs.Close() <--- you do not need this line becuase the "Using" block will take care of this for you.
End Using
End Using
I'm not sure if this will resolve your issue because I can't run your code, but the Using block will automatically take care of closing and cleaning up disposable instances like FileStream and StreamWriter, even if an exception is thrown.
By the way, you should use proper naming conventions (lower camel case) for local variables.

Get the output of a shell Command in VB.net

I have a VB.net program in which I call the Shell function. I would like to get the text output that is produced from this code in a file. However, this is not the return value of the executed code so I don't really know how to.
This program is a service but has access to the disk no problem as I already log other information. The whole service has multiple threads so I must also make sure that when the file is written it's not already accessed.
You won't be able to capture the output from Shell.
You will need to change this to a process and you will need to capture the the Standard Output (and possibly Error) streams from the process.
Here is an example:
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("ApplicationName.exe", "arguments")
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
Console.WriteLine(sOutput)
To get the standard error:
'Add this next to standard output redirect
oStartInfo.RedirectStandardError = True
'Add this below
Using oStreamReader As System.IO.StreamReader = checkOut.StandardError
sOutput = oStreamReader.ReadToEnd()
End Using
Just pipe the output to a text file?
MyCommand > "c:\file.txt"
Then read the file.
Dim proc As New Process
proc.StartInfo.FileName = "C:\ipconfig.bat"
proc.StartInfo.UseShellExecute = False
proc.StartInfo.RedirectStandardOutput = True
proc.Start()
proc.WaitForExit()
Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
For Each ln As String In output
RichTextBox1.AppendText(ln & vbNewLine)
lstScan.Items.Add(ln & vbNewLine)
Next
=======================================================================
create a batch file in two lines as shown below:
echo off
ipconfig
' make sure you save this batch file as ipconfig.bat or whatever name u decide to pick but make sure u put dot bat at the end of it.