VB6 List and Delete All Files in Directory - list

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

Related

Delete all the files after copying in new folder

'Start Button' does the following:
Check the given folder path for .blf files
Copy all the existing .blf files to the destination folder
Show the directory of the folder in text file i,e. where the files are being created
Show the directory where the existing files are being copied i,e. Onto the server
Delete the file from parent folder after copying
How can i do the Point 5..where am i at fault?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Const DestinationDirectory As String = "C:\Users\nha4abt\Desktop\Move_Here"
'Show the parent folder path
TextBox1.Text = "C:\Users\nha4abt\Desktop\Ahmad_examaning_folder"
' Show the destination folder path
TextBox2.Text = DestinationDirectory
For Each FileName As String In directory.GetFiles("C:\Users\nha4abt\Desktop\Ahmad_examaning_folder", "*.blf")
File.Copy(FileName, Path.Combine(DestinationDirectory, Path.GetFileName(FileName)))
ListBox1.Items.Clear()
ListBox1.Items.Add(FileName)
Next FileName
For Each FileName In As String In directory.GetFiles("C:\Users\nha4abt\Desktop\Ahmad_examaning_folder", "*.blf")
File.Delete(Path.GetFileName(FileName))
Next FileName
End Sub
I did that and got the result. It was more like a silly mistake.
Const DestinationDirectory As String = "C:\Users\nha4abt\Desktop\Move_Here"
'Show the parent folder path
Const ParentDirectory As String = "C:\Users\nha4abt\Desktop\Ahmad_examaning_folder"
TextBox1.Text = ParentDirectory
' Show the destination folder path
TextBox2.Text = DestinationDirectory
ListBox1.Items.Clear()
For Each FileName As String In Directory.GetFiles(ParentDirectory, "*.blf")
File.Copy(FileName, Path.Combine(DestinationDirectory, Path.GetFileName(FileName)))
File.Delete(FileName)
ListBox1.Items.Add(FileName)
Next FileName
End Sub

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

Give warning if folder contains more than one file type using RegExp

Using RegExp to search a folder for file types held in an Array.
How can I show a fail if the folder contains more than one different file type but it is perfectly OK to have multiple of the same file type in the folder.
Here's my code:
var AllowedFileTypes = ["orf", "tif", "tiff", "jpg", "jpeg"];
var regex = new RegExp('.+\.(?:' + AllowedFileTypes.join('|')+ ')$','i');
fileList = inputFolder.getFiles(regex);
Thanks

VBS script attempting to write to .rc file returns error

I am trying to find a process by which to edit and write to a resource .rc file; I attempted to use the sample code listed at
How to increment values in resourse file by using vbscript but the last line in both samples returned the same error ( fso.OpenTextFile(rcfile, 2).Write rctext ) :
Error: Invalid procedure call or argument
Code: 800A0005
Source: Microsoft VBScript runtime error
I modified the script to write out to a .txt file and that worked fine, but I'm baffled as to what may be causing the problem writing out to a .rc file.
From the linked sample (simplified)
rctext = fso.OpenTextFile(rcfile).ReadAll
rctext = ....
fso.OpenTextFile(rcfile, 2).Write rctext
The idea is read all the file, and as far as there is no variable holding a reference to the opened file, it is closed, then change what needs to be changed and open again the file, now for writing, and write the changed content to file
And, usually, it works. But sometimes the file opened for reading is not closed fast enough to later open it for writing.
To ensure the file is closed and then can be opened for writing, change the reading code to
set f = fso.OpenTextFile(rcfile)
rctext = f.ReadAll
f.Close
As your line
fso.OpenTextFile(rcfile, 2).Write rctext
does three things (access fso, open file, write to it), there are many things that could go wrong. Please see this answer for ideas wrt to problems concerning the first two actions. Another answer concerns the write.
In your case, the evidence - works with a.txt, but not with b.rc - makes it highly improbable that the file's opening is to blame (so .Close won't save you). I suspect that the .rc contains Unicode (UTF-8/UTF-16) data that the textstream can't encode.
So either use the unicode parameter to read/write open the file with UTF-16 encoding or an ADODB.Stream for UTF-8.
It seems that the answer to my question required both of your answers(#MC ND and #Ekkehard.Horner); also, once I changed the vbs script to open and write to the .rc file in Unicode, which I'm not sure why I have to, the script was able to execute without error.
Here is the vbs script in it's final form:
Const ForReading = 1, ForWriting = 2
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Const DoNotCreate = false
rcFile = "C:\Path\To\RC\File.rc"
major = 4
minor = 3
maint = 2
build = 1
version = major & "," & minor & "," & maint & "," & build
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileObj = fso.OpenTextFile(rcFile, ForReading, DoNotCreate, TristateTrue)
rcText = fileObj.ReadAll
fileObj.Close
Set regex = New RegExp
regex.Global = True
regex.Pattern = "(PRODUCTVERSION|FILEVERSION) \d+,\d+,\d+,\d+"
rcText = regex.Replace(rcText, "$1 " & version)
regex.Pattern = "(""(ProductVersion|FileVersion)"",) ""\d+, \d+, \d+, \d+"""
rcText = regex.Replace(rcText, "$1 """ & Replace(version, ",", ", ") & """")
Set fileObj = fso.GetFile(rcFile)
Set textStream = fileObj.OpenAsTextStream(ForWriting, TristateTrue)
textStream.Write rcText
textStream.Close
The only thing that does not seem to work is the regex for replacing the ProduceVersion|FileVersion values, but hopefully I can hammer that out within a reasonable time.

Quickly enter command-line parameters for Visual Studio debugging?

I want to change my command-line arguments and then debug my executable.
With the default Visual Studio UI, this takes me several tortuous mouse and keyboard actions:
Project ... right click ... Configuration Properties ... Debugging ... Command Arguments ... type args ... ENTER ... F5
Is there a way to make this common action as easy as other common operations, for example, searching all files for a pattern which goes:
CNTL+SHIFT+F ... type search pattern ... ENTER
For example, is there an way to create a custom edit box to allow quick access to the debug command-line arguments? Or a way to have a key-binding pop up a simple "debug dialog" where the args can be entered and debugging started directly? e.g.
ALT+F5 ... type args ... ENTER
I am using C++ and Visual Studio 2010 Express. Thanks!
The extension CLIArgsMadeEasy 2010/2012 is a great little thing that puts the project's debug session's command line arguments right in a little text box on the visual studio toolbar, IMO, its alot easier and less tedious than using macros.
The Link
http://visualstudiogallery.msdn.microsoft.com/8159cd7d-2c81-47f3-9794-a347ec1fba09?SRC=VSIDE
You can just type CLIArgsMadeEasy in your search box in the extensions manager which will find it fairly quickly in the gallery, thats how I installed it, if you need to know. Hope this helps!
Macro below should help. Open "Tools->Macros->Macro Explorer", then create new module, edit it, and copy-paste code below. Required command is SetCommandArgsProperty. UI is not nice, but it works (VS 2005, I hope this will also work in VS 2010). Then add any shortcut you like to run this macro.
Here are some details:
Find startup project
Select it active configuration and find property with name "CommandArguments"
Create edit box with the current value in it
Update property if OK is selected
Sub SetCommandArgsProperty()
Dim newVal As Object
newVal = InputValue(GetCommandArgsPropertyValue())
If TypeOf newVal Is String Then
SetCommandArgsProperty(newVal)
End If
End Sub
Function InputValue(ByVal defaultText As String)
Dim frm As New System.Windows.Forms.Form
Dim btn As New System.Windows.Forms.Button
Dim edit As New System.Windows.Forms.TextBox
edit.Text = defaultText
edit.Width = 100
btn.Text = "OK"
btn.DialogResult = System.Windows.Forms.DialogResult.OK
frm.Text = "Input command line properties"
frm.Controls.Add(btn)
btn.Dock = System.Windows.Forms.DockStyle.Bottom
frm.Controls.Add(edit)
edit.Dock = System.Windows.Forms.DockStyle.Top
frm.Height = 80
frm.Width = 300
If frm.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Return edit.Text
End If
Return System.DBNull.Value
End Function
Function GetCommandArgsProperty() As EnvDTE.Property
Dim solution As Solution
Dim project As Project
Dim sb As SolutionBuild
Dim str As String
Dim cm As ConfigurationManager
Dim config As Configuration
Dim properties As Properties
Dim prop As EnvDTE.Property
solution = DTE.Solution
sb = solution.SolutionBuild
For Each str In sb.StartupProjects
project = solution.Item(str)
cm = project.ConfigurationManager
config = cm.ActiveConfiguration
properties = config.Properties
For Each prop In properties
If prop.Name = "CommandArguments" Then
Return prop
End If
Next
Next
End Function
Function GetCommandArgsPropertyValue()
Return GetCommandArgsProperty().Value
End Function
Sub SetCommandArgsProperty(ByVal value As String)
GetCommandArgsProperty().Value = value
End Sub
At least in Visual Studio 2012, you can use Alt+F7 shortcut to directly access project properties.
Furthermore, the opened Property Pages normally remembers the last opened item, i.e. Configuration Properties -> Debugging.