How to check if file already exists in the folder - vb.net

I am trying to copy some files to folder. I am using the following statement to check if the source fie exists
If My.Computer.FileSystem.FileExists(fileToCopy) Then
But I donot know how to check if file exists in the folder before copying.
Please advise.
Thanks and best regards,
Furqan

Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"
Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.
If System.IO.File.Exists(SavePath) Then
'The file exists
Else
'the file doesn't exist
End If

'In Visual Basic
Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml
Dim FilePath ="C:\MyFolderName" & "\" & FileName 'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.
If System.IO.File.Exists(FilePath) Then
MsgBox("The file exists")
Else
MsgBox("the file doesn't exist")
End If

Related

VBA - File Dialog vs Grab Newest File in Directory?

I currently provide a file dialog to permit a user to select the desired file from a pre-defined directory. Works as expected; I am just looking to reduce steps/interaction.
The files are simple timestamped log files, many in the directory. I do not know the actual filename, but I do know the desired file will always be the NEWEST file in that directory.
Is there a way to select the filename for the file with the newest date/time from a known directory?
Thanks!
I found a good approach here:
finding latest file in a folder and opening it (vba access)
Function NewestFile()
Dim FileName As String
Dim MostRecentFile As String
Dim MostRecentDate As Date
Dim FileSpec As String
'Specify the file type, if any
FileSpec = "*.*"
'specify the directory
Directory = "C:"
FileName = Dir(Directory & FileSpec)
If FileName <> "" Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(Directory & FileName)
Do While FileName <> ""
If FileDateTime(Directory & FileName) > MostRecentDate Then
MostRecentFile = FileName
MostRecentDate = FileDateTime(Directory & FileName)
End If
FileName = Dir
Loop
End If
NewestFile = MostRecentFile
End Function
`
A few minor adjustments to suit my needs; works as desired.

How to get the browse file path in text box using VBA?

How to get the browse file name into text box ? if get the file path, how to split the file name?
I tried application.GetOpenFilename("Text Files(*.txt),*.txt")
Please advise to display into the text box and how to split the exact file name only to read the text file?
Don't waste your time reinventing the wheel: the FileSystemObject will do this for you.
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Sheet1.TextBox1.Text = FSO.GetFilename("C:\mydir\myfile.dat")
The textbox now contains the text myfile.dat.
The Dir function will give you the file name as long as it's a file that exists - and yours will be if you use GetOpenFilename.
Sub GetFileName()
Dim sFullName As String
Dim sFileName As String
sFullName = Application.GetOpenFilename("*.txt,*.txt")
sFileName = Dir(sFullName)
Debug.Print sFullName, sFileName
End Sub
Here is a VBA routine to return the file name stripped of its path. Its easily modified to return the path instead, or both.
'====================================================================================
' Returns the file name without a path via file open dialog box
'====================================================================================
' Prompts user to select a file. Which ever file is selected, the function returns
' the filename stripped of the path.
Function GetAFileName() As String
Dim someFileName As Variant
Dim folderName As String
Dim i As Integer
Const STRING_NOT_FOUND As Integer = 0
'select a file using a dialog and get the full name with path included
someFileName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If someFileName <> False Then
'strip off the folder path
folderName = vbNullString
i = 1
While STRING_NOT_FOUND < i
i = InStr(1, someFileName, "\", vbTextCompare) 'returns position of the first backslash "\"
If i <> STRING_NOT_FOUND Then
folderName = folderName & Left(someFileName, i)
someFileName = Right(someFileName, Len(someFileName) - i)
Else 'no backslash was found... we are done
GetAFileName = someFileName
End If
Wend
Else
GetAFileName = vbNullString
End If
End Function
Easiest way is to simply read from the final "\";
tbx.text = mid$(someFileName, 1 + InStrRev(someFileName, "\"), Len(someFileName))
Button1 click
OpenFileDialog1.ShowDialog()
Me.TextBox1.Text = OpenFileDialog1.FileName
End Sub
Textbox1 change
Dim File As System.IO.FileInfo
File = My.Computer.FileSystem.GetFileInfo(TextBox1.Text)
Dim Path As String = File.DirectoryName
TextBox2.Text = Path
Dim fileName As String = File.Name
TextBox3.Text = fileName
End Sub

Dir Function in Excel 2010 VBA not working

I am trying to loop through a given directory to find the latest downloaded csv file. For some reason my Dir function won't find any file even if the file does exist. I am not totally familiar with VBA so i may perhaps be missing some sort of reference to perform the Dir function, but I can't find anything online that tells me I need to. All the examples and forums use Dir just like I do, but I can't get mine to work. Here is the code, please tell me if you can see what I am doing wrong:
Public Function Get_File() as string
Dim filePath As String
ChDir ("..")
filePath = CurDir
'Goes back to Documents directory to be in same directory as macro
ChDir (filePath & "\Documents")
filePath = filePath & "\Downloads\test.txt"
filePath = getLatestFile(filePath)
Get_File = filePath
End Function
Public Function getLatestFile(pathToFile As String) As String
Dim StrFile As String
Dim lastMod As Variant
Dim nextMod As Variant
Dim lastFileName As String
StrFile = Dir(pathToFile)
lastFileName = StrFile
lastMod = FileDateTime(StrFile)
While Len(StrFile) > 0
Debug.Print StrFile
StrFile = Dir
nextMod = FileDateTime(StrFile)
If nextMod > lastMod Then
lastFileName = StrFile
lastMod = nextMod
End If
Wend
getLatestFile = lastFileName
End Function
The test.txt file is in my Downloads file and the filePath string prints out to be the correct path, but I keep getting an error stating that it can't find the file. It fails at the first use of Dir(pathToFile). Any help would be greatly appreciated.
Dir() only returns the filename portion of the path, i.e., it does not return the folder portion. For example,
Dir("C:\MyPath\MyFile.txt")
returns MyFile.txt not C:\MyPath\MyFile.txt

How search for a folder and copy the folder in visual basic.net?

I can't find how to search for a folder (directory) that contains a string and copy all the folders (directory) that contain that string to another directory. So you search for the name of the directory, not the files in the directory.
For example: 'KTNPRK' in E:\ gives:
E:\KTNPRK1, E:\AZNKTNPR76, etc...
Here is an example of how to move the directories:
Dim sSourcePath As String
Dim sDestPath As String
Dim sTextToFind As String
sSourcePath = "D:\Temp"
sDestPath = "D:\Temp1"
sTextToFind = "test"
For Each sDir In Directory.GetDirectories(sSourcePath, "*" & sTextToFind & "*")
Directory.Move(sDir, Path.Combine(sDestPath, Path.GetFileName(sDir)))
Next
In order to copy all of the files in the folders, the loop can be changed to:
Dim sFullDestDir As String
sFullDestDir = Path.Combine(sDestPath, IO.Path.GetFileName(sFullSourceDir))
' Create the directory if it doesn't exist
If Not Directory.Exists(sFullDestDir) Then
Directory.CreateDirectory(sFullDestDir)
End If
' Copy the files in the directory
' If subfolders are to be copied, this logic can be turned into a recursive method.
For Each sFileName As String In Directory.GetFiles(sFullSourceDir)
File.Copy(sFileName, Path.Combine(sFullDestDir, IO.Path.GetFileName(sFileName)))
Next

Search file in folder based on input from user, copy that file into a new folder

I have a folder that contains a lot of pictures. I need to copy the pictures in that folder based on the input by the user and copy it into a new folder:
User enters input.
The code needs to search for the pictures in the folder based on the input.
If found, the pictures is than move to a new folder/another folder.
How do I do this?
This is an example of how to do it. I don't know what your "user input" is, so I just made an assumption. Rectify as appropriate.
Sub CopySomeFiles()
Dim FSO, sourceFolder, currentFile, filesInSourceFolder
Dim strSourceFolderPath As String
Dim strDestinationFolderPath As String
Dim strUserInput As String
Set FSO = CreateObject("Scripting.FileSystemObject")
' Figure out which file to copy from where to where
strUserInput = InputBox("Please enter name of file to copy.")
strSourceFolderPath = "C:\MySourceFolder"
strDestinationFolderPath = "C:\MyDestinationFolder"
Set sourceFolder = FSO.GetFolder(strSourceFolderPath)
Set filesInSourceFolder = sourceFolder.Files
' Look at all files in source folder. If name matches,
' copy to destination folder.
For Each currentFile In filesInSourceFolder
If currentFile.Name = strUserInput Then
currentFile.Copy (FSO.BuildPath(strDestinationFolderPath, _
currentFile.Name))
End If
Next
End Sub