【问题标题】:Why System.IO.File.Exists doesn't take if else statement为什么 System.IO.File.Exists 不采用 if else 语句
【发布时间】:2015-10-04 14:44:02
【问题描述】:

在为图像文件运行以下代码时遇到if 条件问题:

    Dim mainFolder As String = "\\Users\No_Image_Available.png"
    Dim saveDirectory As String = "\\IMAGE\"
    Dim Filename As String = System.IO.Path.GetFileName(mainFolder)
    Dim mainSavePath As String = System.IO.Path.Combine(saveDirectory, Filename)

    If System.IO.File.Exists(mainSavePath) Then
        'do nothing
    Else
        'file doesn't exist
        My.Computer.FileSystem.CopyFile("\\Users\No_Image_Available.png", "\\IMAGES\No_Image_Available.png")

    End If

如果文件不存在,那么它将接受 IF Not existIF exist 的 if 语句...但是,如果文件已经存在,则无论它是否在正确的 if 条件下,它都会接受 copy 参数与否。

这是为什么呢?就好像它仍然读取并接受第一个 'do nothing' 条件一样。

仅供参考-您看到的路径是假的

【问题讨论】:

  • 问题与File.Exists() 的不同之处在于传递给它的路径/文件名。 the paths you see are fake为真实答案提供真实代码
  • 在引用 stackoverflow 时,有人得到 .Exist 为他们工作,这就是我使用它的原因。这是迄今为止我所知道的唯一一个可以使用的。 @Plutonix
  • \\IMAGE\\\Users\No_Image_Available.png 那是一条有效的路径吗?除非您在尝试伪造路径名时打错字。
  • 来自MSDN:This method also returns false if path is Nothing, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

标签: vb.net directory file-copying system.io.file


【解决方案1】:

问题是它们是服务器目录。我做了有效的更正。

Dim Filename = "No_Image_Available.png"
    Dim savePathcopy As String = Server.MapPath("~/IMAGES/")
    Dim pathToCheckCopy As String = savePathcopy + Filename

    'Dim mainSavePath As String = System.IO.Path.Combine(saveDirectory, Filename)
    If (System.IO.File.Exists(pathToCheckCopy)) Then
        ' If System.IO.File.Exists(noImg) = True Then
    Else
        'file doesn't exist
        My.Computer.FileSystem.CopyFile("\\..\Dev\web\WebUsers\...\..\Classified_Ads_V2\No_Image_Available.png", "\\...\Dev\web\WebUsers\...\..\...\IMAGES\No_Image_Available.png")
    End If

【讨论】:

  • 如果我可以问为什么会这样? @JoelCoehoorn
  • 对不起。完全没有看到链接部分 XD 好的我会审查谢谢! @JoelCoehoorn
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 1970-01-01
  • 2010-10-01
  • 2016-08-10
  • 2016-07-05
相关资源
最近更新 更多