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

如何在VB.NET中保存用户输入的源路径与目标路径

Add Save/Load Functionality for Paths in Your VB.NET File Copy App

Hey there! Since you're building your first VB.NET app and want to add a way to save the source and destination paths, let's keep it simple and use a text file to store these settings—it's easy to implement and perfect for a basic app. Here's the updated code with the save functionality, plus a bonus load button to recall the saved paths later:

Updated Full Code

Imports System.IO ' Add this import at the top for file operations

Public Class Form1
    ' Define a path to store settings - using AppData to avoid permission issues
    Private ReadOnly settingsPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FileCopySettings.txt")

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TextBox1.Text = ""
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            TextBox1.Text = FolderBrowserDialog1.SelectedPath
        Else
            TextBox1.Text = ""
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        TextBox2.Text = ""
        If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
            TextBox2.Text = FolderBrowserDialog1.SelectedPath
        Else
            TextBox2.Text = ""
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Me.Refresh()
        Label1.Text = "Working... Please do not close this window. Even if says not responding "
        Dim location As String = TextBox1.Text
        Dim locationsave As String = TextBox2.Text

        Try
            Me.Refresh()
            My.Computer.FileSystem.CopyDirectory(location, locationsave, True)
            Label1.Text = "Completed! Backed up to: " & locationsave
        Catch ex As Exception
            MessageBox.Show("Either your source location or destination location does not exist! Please check them and try again.", "Oops!")
        End Try
    End Sub

    ' New button to save paths
    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        ' Check if both paths are filled in
        If String.IsNullOrWhiteSpace(TextBox1.Text) Or String.IsNullOrWhiteSpace(TextBox2.Text) Then
            MessageBox.Show("Please select both source and destination paths first!", "Missing Paths")
            Return
        End If

        ' Write paths to the settings file (each path on a new line)
        Try
            My.Computer.FileSystem.WriteAllText(settingsPath, $"{TextBox1.Text}{Environment.NewLine}{TextBox2.Text}", False)
            MessageBox.Show("Paths saved successfully!", "Saved")
        Catch ex As Exception
            MessageBox.Show($"Failed to save paths: {ex.Message}", "Error Saving")
        End Try
    End Sub

    ' Bonus: Button to load saved paths
    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        ' Check if the settings file exists
        If Not File.Exists(settingsPath) Then
            MessageBox.Show("No saved paths found!", "No Settings")
            Return
        End If

        Try
            ' Read lines from the file
            Dim savedPaths As String() = File.ReadAllLines(settingsPath)
            If savedPaths.Length >= 2 Then
                TextBox1.Text = savedPaths(0)
                TextBox2.Text = savedPaths(1)
                MessageBox.Show("Paths loaded successfully!", "Loaded")
            Else
                MessageBox.Show("Saved settings are invalid!", "Invalid Settings")
            End If
        Catch ex As Exception
            MessageBox.Show($"Failed to load paths: {ex.Message}", "Error Loading")
        End Try
    End Sub

    ' Optional: Load paths automatically when the form opens
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If File.Exists(settingsPath) Then
            Try
                Dim savedPaths As String() = File.ReadAllLines(settingsPath)
                If savedPaths.Length >= 2 Then
                    TextBox1.Text = savedPaths(0)
                    TextBox2.Text = savedPaths(1)
                End If
            Catch ex As Exception
                ' Ignore startup errors to avoid annoying the user
            End Try
        End If
    End Sub
End Class

Key Details to Note:

  • Settings Storage: We're using the ApplicationData folder (a hidden, user-specific folder) to store the settings file. This avoids permission issues that might happen if you try to save to the program's installation folder.
  • Save Button (Button4): Checks if both paths are filled before saving, then writes them to a text file (each path on a separate line).
  • Load Button (Button5): Reads the saved paths from the text file and populates the text boxes.
  • Auto-Load on Startup: The Form1_Load event tries to load saved paths automatically when the app opens, which is a nice user touch.
  • Error Handling: Each file operation has basic error handling to catch issues like permission problems or corrupted settings files.

Quick Setup Steps:

  1. Add two new buttons to your form: name one Button4 (set its Text to "Save Paths") and the other Button5 (set its Text to "Load Paths").
  2. Make sure you add the Imports System.IO line at the very top of your code file—it's needed for file-related operations.

That's it! Now your users can save their favorite source/destination pairs and load them back easily.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:54:01