【问题标题】:How to check if file already exists in the folder如何检查文件夹中是否已存在文件
【发布时间】:2011-12-02 06:48:16
【问题描述】:

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

 If My.Computer.FileSystem.FileExists(fileToCopy) Then

但我不知道如何在复制前检查文件夹中是否存在文件。 请指教。

感谢和最好的问候, 福尔坎

【问题讨论】:

  • 如果我理解正确,您实际上是在问如何从原始路径中提取文件名并查看不同目录中是否存在同名文件?这是我现在唯一有意义的解释,因为您显然已经知道如何查看文件是否存在。如我的示例所示,您可以使用system.io.path 类来操作路径。请让我们知道这是否真的是您的意思。
  • 请注意,在检查文件是否存在的测试和程序开始写入文件的那一刻之间,进程可以创建文件。

标签: vb.net


【解决方案1】:
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

【讨论】:

  • 我想我终于明白你的意思了,如果更新的代码更接近你的意图,请告诉我。
  • 对于困惑的 Excel 宏用户,请参阅 stackoverflow.com/a/11573970/733092
【解决方案2】:

'在 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

【讨论】:

  • 我怀疑这是否有帮助甚至根本有效。为了说服别人,请解释您的提案是如何运作的以及为什么它有助于解决问题。
猜你喜欢
  • 1970-01-01
  • 2011-11-15
  • 2010-12-10
  • 2012-02-05
  • 2013-03-12
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多