You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET复制含GES的.ini文件:如何仅复制文件而非完整路径?

解决VB.NET复制文件时生成源文件完整路径的问题

你遇到的问题根源在于foundFile变量存储的是包含完整路径的文件字符串,直接把它和destination拼接的话,相当于把源文件的整个路径都追加到目标路径后面了,自然会生成重复的文件夹结构。

要只复制文件本身,关键是从完整路径中提取出纯文件名,然后再和目标路径拼接。这里有两种简单的实现方式:

方法1:使用Path.GetFileName(推荐)

System.IO.Path类提供了很多处理路径的实用方法,GetFileName可以直接从完整路径中剥离出文件名。记得先导入System.IO命名空间,或者直接写完整命名空间。

修改后的代码如下:

' 记得导入System.IO命名空间,或者使用完整的System.IO.Path
For Each foundFile As String In My.Computer.FileSystem.GetFiles(
    FileSource, 
    Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, 
    "*GES*.ini"
)
    ' 获取纯文件名
    Dim fileName As String = System.IO.Path.GetFileName(foundFile)
    ' 用Path.Combine拼接路径,自动处理分隔符问题(比&更安全)
    Dim targetPath As String = System.IO.Path.Combine(destination, fileName)
    My.Computer.FileSystem.CopyFile(foundFile, targetPath)
Next

方法2:使用My.Computer.FileSystem的API

如果你习惯用VB.NET的My命名空间,也可以通过GetFileInfo来获取文件名:

For Each foundFile As String In My.Computer.FileSystem.GetFiles(
    FileSource, 
    Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, 
    "*GES*.ini"
)
    Dim fileInfo = My.Computer.FileSystem.GetFileInfo(foundFile)
    Dim targetPath As String = System.IO.Path.Combine(destination, fileInfo.Name)
    My.Computer.FileSystem.CopyFile(foundFile, targetPath)
Next

额外注意点

  • 建议使用Path.Combine来拼接路径,而不是直接用&:它会自动处理目标路径末尾是否有\的问题,避免出现类似C:\DestC:\Source\file.ini这种错误路径。
  • 如果目标文件夹里已经存在同名文件,默认会抛出异常,你可以在CopyFile方法里添加第三个参数True来覆盖文件:My.Computer.FileSystem.CopyFile(foundFile, targetPath, True)

内容的提问来源于stack exchange,提问作者ArunAshokan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:29:45