因此,我正在从事一个项目,目的是允许我的用户从那里的个人文件中选择一个mp3 / wav文件,并将其保存在我的程序目录中,以便以后可以访问。
Public Class Uploader_Control
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button_Upload.Click 'Button click triggers open file dialog
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.Title = "Upload A Song"
OpenFileDialog1.Filter = "Audio Files|*.mp3; *.wav"
OpenFileDialog1.Multiselect = False
OpenFileDialog1.ShowDialog()
Dim New_Upload As String = OpenFileDialog1.FileName 'Sets 'New_Upload' to the location of the selected file.
Dim Upload_Path = Get_Upload_Path() 'Triggers function to find the destination path that i want the file to be copied too
End Sub
Function Get_Upload_Path() 'Tries to find the location for the file to saved too
Dim Upload_Path As String = Application.ExecutablePath
Upload_Path = Upload_Path.Substring(0, Upload_Path.LastIndexOf("/")) & "\Resources\"
Return Upload_Path
End Function
我尝试了几种方法尝试将其复制,但是我似乎找不到找到将文件复制到目录中的方法。如果任何人都可以对我可以实现的方法提供任何见解,将不胜感激。
答案 0 :(得分:2)
首先要解决的是您的GetUploadPath。
Function Get_Upload_Path() as String
Dim newPath As String = Application.ExecutablePath
newPath = Path.Combine(Path.GetDirectoryName(newPath), "Resources")
Return newPath
End Function
在这里,我正在使用安全的Path类方法来提取您的文件夹并追加Resource文件夹。您的代码改为使用字符“ /”,这不是Windows中的默认路径分隔符。可能您在那里会遇到异常
最后,您使用File.Copy复制文件,但请记住,应始终为File.Copy提供文件名。复制源和目标参数,而不仅仅是目录名
if OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Dim newPath = Get_Upload_Path()
Dim file = Path.GetFileName(OpenFileDialog1.FileName)
Dim newUploadName = Path.Combine(newPath, file)
File.Copy(OpenFileDialog1.FileName, newUploadName)
End If
答案 1 :(得分:1)
最简单的方法是使用System.IO.FileInfo:
Dim file as New FileInfo(path)
file.CopyTo(newPath)
答案 2 :(得分:0)
此解决方案将起作用,尝试使内容与原始内容保持接近:
'Set up and open file dialog
OpenFileDialog1.Title = "Upload A Song"
OpenFileDialog1.Filter = "Audio Files|*.mp3; *.wav"
OpenFileDialog1.Multiselect = False
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.FileName = String.Empty
'Only proceed if OK pressed
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
'Get Destination Path
Dim Upload_Path As String = IO.Path.Combine(Application.StartupPath, "Resources")
If IO.Directory.Exists(Upload_Path) Then
'Copy file
IO.File.Copy(OpenFileDialog1.FileName, IO.Path.Combine(Upload_Path, IO.Path.GetFileName(OpenFileDialog1.FileName)))
End If
End If
在您尝试复制之前,我添加了一个文件夹是否存在的检查。
您需要考虑的其他事项:
如果该文件夹不存在,请考虑创建它或发出消息。
您正在将文件复制到您的apps目录。根据您应用的位置,您可能会遇到“权限”问题。
是否会引用您在工作中加载的原始文件?音频文件的引用列表,将其加载而不进行复制,然后在需要时进行处理?
答案 3 :(得分:0)
此外,如果您愿意,也可以使用以下方法移动它:
My.Computer.FileSystem.MoveFile(c:\\source\my.mp3, d:\\destination\my.mp3)
如果没有,请改用CopyFile。