首页 > 解决方案 > 想要使用 VB.net 中的按钮将文件从一个位置传输到另一个位置

问题描述

我的服务器上有一个 Excel 文件(比如 xyz.xlsx),但我想获取该文件并在我的桌面上本地保存,每当我按下表单上的“移动”按钮时。请指导我如何做到这一点可以做到。我现在正在使用 Visual Studio 2017

标签: vb.net

解决方案


你有两个简单的选择。

如果您想将此作为培训练习,请查看 System.IO 类。

System.IO.File.Move(source$, destination$) will suffice.

您可以通过一些错误检查来改进这一点,例如

System.IO.Directory.Exists(sourcePath$)
System.IO.Directory.Exists(destPath$)

然后,您可以随意使用字符串格式和错误处理。

如果您所做的只是复制一个文件并且这是您的整个软件,我建议您改为在 CMD 中进行

如果需要,可以从 VB 调用相同的方法。Process.Start("ROBOCOPY " & source$ & " " & destination$ & " " & flags)

这样做的好处是它与您的主代码是一个单独的过程,这意味着您可以在很长一段时间内保留一个非常大的文件复制而不会挂起您自己的代码。

''' <summary>
''' Copies the file at destination Source to the folder DestinationPath (and creates the folder if it doesn't exist)
''' </summary>
''' <param name="Source">Format C:\Users\username\documents\randomstuff\unnecessaryfolder\newfolder\myfile.txt</param>
''' <param name="DestinationPath">Format (and Default path) C:\Users\username\Desktop\ </param>
Public Sub MoveFile(Source As String, DestinationPath As String)
    If DestinationPath = "" Then
        DestinationPath = "C:\Users\" & My.User.Name & "\Desktop\" 'default path
    End If
    Dim FileName
    Dim src() As String = Source.Split("\")
    FileName = src(src.Count - 1) 'returns the name of the file in the full path
    Try
        If Not IO.File.Exists(Source) Then Throw New Exception("Wrong file, you plonka!")
        If Not IO.Directory.Exists(DestinationPath) Then IO.Directory.CreateDirectory(DestinationPath)
        IO.File.Copy(Source, DestinationPath & FileName)
    Catch ex As Exception
        Throw ex
    End Try
End Sub

推荐阅读