VB.Net 选择文件名而不打开文件

问题描述 投票:0回答:1

我正在使用 VB.net,需要一个对话框才能选择要排除的文件名。 问题是,当您选择要排除的文件(例如 pagefile.sys)时,单击“确定”后,会出现一条错误消息,指出该文件正在使用中。显然该文件正在使用中,我只是想获取文件名,而不是实际打开该文件。那么如何选择文件名,但不能打开它呢?我的代码如下

    Using dialog As New OpenFileDialog
        dialog.Title = "Select a file to exclude from the backup"
        dialog.InitialDirectory = "C:\"
        If dialog.ShowDialog <> DialogResult.OK Then Return
        MsgBox(dialog.FileName)
    End Using
vb.net
1个回答
0
投票

将“ValidateNames”属性设置为 False 可消除有关文件“正在使用”的特定提示。

Using dialog As New OpenFileDialog
        dialog.Title = "Select a file to exclude from the backup"
        dialog.InitialDirectory = "C:\"
        dialog.ValidateNames = False   ' add this line to your existing code
        If dialog.ShowDialog <> DialogResult.OK Then Return
        MsgBox(dialog.FileName)
    End Using

理论上,这并不完全是一个完美的解决方案,因为微软对“ValidateNames”属性的描述并没有真正提到任何有关“使用中”文件的内容。 因此,请谨慎使用此解决方案 - 如果您确实需要“ValidateNames = True”提供的功能,那么您显然会遇到此问题中提出的特定问题。 https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.filedialog.validatenames?view=windowsdesktop-8.0

© www.soinside.com 2019 - 2024. All rights reserved.