如何检查文件夹中是否已存在文件

18

我正在尝试将一些文件复制到文件夹中。我使用以下语句检查源文件是否存在:

 如果 My.Computer.FileSystem.FileExists(fileToCopy) Then 

但是我不知道如何在复制之前检查文件是否存在于文件夹中。请给予建议。

谢谢并致以最好的问候, Furqan


如果我理解正确的话,您实际上是在询问如何从原始路径中提取文件名,并查看是否存在具有相同名称的文件在不同的目录中?这是我现在能想到的唯一合理的解释,因为您显然已经知道如何查看文件是否存在。您可以使用system.io.path类来操作路径,就像我的示例所示。如果这确实是您的意思,请告诉我们。 - Bradley Uffner
请注意,在检查文件存在性的测试和程序开始写入文件之间,可能会有一个进程创建文件。 - Emond
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

我想我终于明白你想表达什么了,如果更新后的代码更接近你的意图,请告诉我。 - Bradley Uffner
对于困惑的Excel宏用户,请参见https://dev59.com/oGgu5IYBdhLWcg3wGjdF#11573970。 - Noumenon

1
“在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
我怀疑这是否有所帮助,甚至是否有效。如果您想让我改变看法,请解释一下您的建议是如何工作的,以及为什么它有助于解决问题。 - Yunnosch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接