Listing of files from directory and sub-directories - list

I am using the following code. But it fails to deliver the output in the textbox t1.
Imports System.IO
Public Class Form1
Dim fp As String
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Click
If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
fp = FolderBrowserDialog1.SelectedPath
t2.Text = fp
End If
End Sub
Private Sub b2_Click(sender As Object, e As EventArgs) Handles b2.Click
Dim filelist As String() = Directory.GetFiles(fp, SearchOption.AllDirectories)
For Each filename As String In filelist
t1.AppendText(filename)
Next
End Sub
I am unable to trace where lies the mistake. Help is needed
Thanks

I found out the silly thing was to insert the type of files i.e., "." in GetFiles.

Related

Generalize regex XML validation

I am looking to make my code better by letting for example Dim IDNumbers() As String = 'SOMETHING' instead of writing out the list of strings individually like {"0", "1", "2", "3", "4"}. I want to be able to read all the ID, student name and birthday nodes from my XML file without having to physically go and list them all. I am unsure how to do this If anybody could help with sample code that would be great. The reason for this is that if I modify my code in the file I have to change it in my vb code too.
Try following :
Imports System.Xml
Imports System.Xml.Linq
Imports System.Globalization
Module Module1
Const FILENAME As String = "c:\temp\test.xml"
Sub Main()
Dim doc As XDocument = XDocument.Load(FILENAME)
Dim results = doc.Descendants("student").Select(Function(x) New With { _
.id = CType(x.Element("ID"), string), _
.name = CType(x.Element("student_name"), string), _
.birthday = CType(x.Element("birthday"), string) _
}).ToList()
End Sub
End Module

OpenFileDialog component in Visual Studio 2017

I'm working on a VB project in Visual Studio 2017. It's a Blank App (Universal Windows) project. When trying to work with this type of app, it doesn't seem to have an OpenFileDialog like the Windows Forms App (.NET Framework) has. Is there a way to do one of two things:
Create a Windows Forms App that has the same look and feel as the Blank App (Universal Windows)
Add the OpenFileDialog option to the Blank App (Universal Windows)
The following code is a VB version of the MS example at https://learn.microsoft.com/en-us/uwp/api/Windows.Storage.Pickers.FileOpenPicker.
Imports Windows.Storage
Imports Windows.Storage.Pickers
Public NotInheritable Class MainPage
Inherits Page
Private Async Sub Button_Click(sender As Object, e As RoutedEventArgs)
Dim openPicker As New FileOpenPicker()
openPicker.ViewMode = PickerViewMode.Thumbnail
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary
openPicker.FileTypeFilter.Add(".jpg")
openPicker.FileTypeFilter.Add(".jpeg")
openPicker.FileTypeFilter.Add(".png")
Dim file As StorageFile = Await openPicker.PickSingleFileAsync()
If (file IsNot Nothing) Then
Debug.WriteLine($"Picked File: {file.Name}")
Else
Debug.WriteLine("Operation Cancelled.")
End If
End Sub
End Class
What I ended up doing to get the same(ish) look was to just play around with some of the properties of the form and the buttons. This gave me the look that I was after. It wasn't exact, but I'll take it.
As for OpenFileDialog, I ended up using the following:
Dim myStream As IO.Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
' Open file dialog parameters
openFileDialog1.InitialDirectory = "c:\" ' Default open location
openFileDialog1.Filter = "Executable Files (*.exe)|*.exe|All Files (*.*)|*.*"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Insert code to read the stream here.
Textbox1.Text = openFileDialog1.FileName
' Even though we're reading the entire path to the file, the file is going to be ignored and only the path will be saved.
' Mostly due to me lacking the ability to figure out how to open just the directory instead of a file. Resolution threadbelow.
' http://www.vbforums.com/showthread.php?570294-RESOLVED-textbox-openfiledialog-folder
' Setting the public variable so it can be used later
Dim exepath As String
exepath = IO.Path.GetDirectoryName(Me.txtExeLocation.Text)
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If

Unable to copy objects on S3

I'm trying to copy video files from in my store from one folder to another. The files are all under 1GB. Everytime I try, I get an exception.
Name of S3 store: BandMedia
example files:
SourceFileName: VideoFiles/Band1/video1_38372836.mp4
DestinationFileName: VideoFiles/Band2/video1_47296110.mp4
The folder "VideoFiles" exist on my AWS S3 store.
However, the band name for the DestinationFileName is new(Band2).
So maybe it's not copying over because of that? Would I need to create the folder for the band first, and then do the copy? But I'm pretty sure I read in the SDK documentation that if the folder doesn't exist, it will be automatically created.
Here's the code that copied pretty much from the AWS SDK examples:
Try
Dim AppSettings As Specialized.NameValueCollection = System.Configuration.ConfigurationManager.AppSettings()
Dim AwsAccessKey As String = "xxxxxx"
Dim AwsSecretKey As String = "11111"
Dim AwsBucketName = "BandMedia"
Dim AwsRegionEndpoint As String = AwsEndPoint
Dim AwsRegionEndpointObj As RegionEndpoint = RegionEndpoint.GetBySystemName(AwsRegionEndpoint)
Dim s3 = New Amazon.S3.AmazonS3Client(AwsAccessKey, AwsSecretKey, AwsRegionEndpointObj)
Dim cRequest As CopyObjectRequest
Dim cReponse As CopyObjectResponse
cRequest = New CopyObjectRequest()
With cRequest
.SourceBucket = AwsBucketName
.DestinationBucket = AwsBucketName
.SourceKey = SourceFileName
.DestinationKey = DestinationFileName
.CannedACL = S3CannedACL.PublicRead
End With
cReponse = s3.CopyObject(cRequest)
Return cReponse.HttpStatusCode = 200
Catch ex As AmazonS3Exception
Return False
End Try
Here's the error:
Exception thrown: 'System.Exception' in videoMusicApp.dll Exception
while copying file VideoFiles/Band1/video1_38372836.mp4 to
VideoFiles/Band2/video1_47296110.mp4
Another thought...maybe it's because it's on the same store?
Honestly, I don't know though.
Could anyone help me out? Thanks!

vb.net Regex remove a tags with mailto

I have a text for example:
" Visit www.flexstaff.com for details
Email rachel#flexstaff.com apply online."
I would like to delete only the a tags that contain "mailto" so
rachel#flexstaff.com will become
rachel#flexstaff.com
I have this regex:
Dim rgxMailTo = New Regex("<a\b\s[^<>]*(?<=#.*)>|(?<=#.*)</a>",RegexOptions.IgnoreCase)
Dim ret As String = rgxMailTo.Replace(text, Environment.NewLine)
But it selects other a tags as well.
Use the below regex and then replace the match with $1.
<a\b\s*[^<>]*\bmailto\b[^<>]*>([^<>]*)<\/a>
DEMO
To select only the tags.
<a\b\s*[^<>]*\bmailto\b[^<>]*>|(?<=<a\b\s*[^<>]*\bmailto\b[^<>]*>[^<>]*)<\/a>
If your text is of uncertain source (so it was not all generated in 100% predictable way), using regex is a very bad idea - trust me, I've been there.
One option is to use Html Agility Pack, and load the HTML as an XElement (C#, as I have sample on hand):
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(HTML);
htmlDoc.OptionOutputAsXml = true;
using (var stream = new MemoryStream())
{
htmlDoc.Save(stream);
stream.Position = 0;
var xelement = XElement.Load(stream);
DoStuffToXElement(xelement);
}
Note, that in case you have just a fragment without a root element:
Link
<img src="#"/>
Remember to wrap it in something neutral, like htmlDoc.LoadHtml("<div>"+HTML+"</div>");
Now you can use LinqToXml to find whatever you need, traverse the tree or do anything quite safely:
xHtml
.Descendants()
.Where(e=>e.Name.LocalName.Equals("a", StringComparison.OrdinalIgnoreCase)
&& e.Attribute("href") != null
&& e.Attribute("href").Value.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase))
.Remove();
Final note: this is nearly always much slower than regex - if time is important (for example you do it at every page load or sth) it might be too slow, but I guess this kind of processing can be done beforehand?
You can use the power of LINQ to XML like this:
Imports System.Text.RegularExpressions
Imports System.Xml.Linq
Imports System.Xml
Imports System.Xml.XPath
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim str As String = "Visit www.flexstaff.com for details\nEmail rachel#flexstaff.com apply online."
Dim xDoc As XDocument = XDocument.Parse("<?xml version= '1.0'?><root>" + str + "</root>")
Dim query = xDoc.XPathSelectElements("//a[contains(#href,'mailto')]")
For Each element In query
element.Remove()
Next element
Dim Res As String = xDoc.ToString().Replace("<root>", String.Empty).Replace("</root>", String.Empty)
End Sub
End Class
Outoput (Res):
Visit www.flexstaff.com for details\nEmail apply online.

VB6 List and Delete All Files in Directory

I need to grab the names of all files in a directory, I am currently using this code:
Dim File As String
File = Dir$(Environ("AppData") & "\*.exe")
Do While Len(File)
MsgBox "Deleting: " & Environ("AppData") & "\" & File
Kill Environ("AppData") & "\" & File
File = Dir$
Loop
This works fine, however it does not display hidden/system files, or files with any attributes other than 'normal', how can I list files no matter their attributes?
I have tried this as well, which has the same outcome:
Kill Environ("AppData") & "\*.*"
The Dir function can take a second parameter for attributes:
File = Dir$(Environ("AppData") & "\*.exe", vbHidden & vbSystem)
You can fin more about the Dir function here.
I pretty much always use the Microsoft Scripting Runtime for file I/O from VB6. It just does more, and it does it better and more easily. One tiny downside is that your VB program is now dependent on the Scripting Runtime DLL (scrrun.dll), which you should add as a reference from within the VB6 IDE.
Here's an example that deletes all files from a folder.
' Note: This code is untested.
Sub Main()
DeleteAllFilesInFolder Environ("App_Data")
End Sub
Sub DeleteAllFilesInFolder(strFolder As String)
Dim fso As Scripting.FileSystemObject
Dim objFolder As Scripting.Folder
Dim objFile As Scripting.File
Set fso = New Scripting.FileSystemObject
Set objFolder = fso.GetFolder(strFolder)
For Each objFile in objFolder.Files
objFile.Delete force:=True
Next
End Sub