18

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

2
  • If I understand correctly you are actually asking how to pull off the filename from the original path and see if a file with that same name exists within a different directory? That's the only interpretation that makes sense to me now, since you obviously already know how to see if a file exists. You can use the system.io.path class to manipulate paths as my example shows. Please let us know if this is actually what you mean. Dec 2, 2011 at 12:34
  • Please note that in between the test that checks for the existence of the file and the moment the program starts to write to the file, a process could create the file.
    – Emond
    Dec 26, 2019 at 10:52

2 Answers 2

66
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
2
1

'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
1
  • 1
    I doubt that this helps or even works at all. To convince be otherwise, please explain how your proposal works and why it helps to solve the problem.
    – Yunnosch
    Dec 26, 2019 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.