Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

string - How do i save a pdf file to a desktop directory using vb.net?

I am creating a PDF form in vb.net and saving it to my desktop. The user inputs a name into the textbox and when they click the button the pdf file is created and saved to my desktop.

The issue I am having is that the pdf is being saved like this:


I do not understand why "Desktop" is showing in the front. Is there a way to fix this?

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

            Dim pdfdoc As New Document(PageSize.A4, 15, 15, 30, 30)

            Dim filename As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + TextBox1.Text + " report.pdf"
            Dim file As New FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)
            PdfWriter.GetInstance(pdfdoc, file)

        Catch ex As Exception
            MessageBox.Show("PDF could not be generated!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End Try

End Sub

End Class

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use System.IO.Path.Combine to assemble paths with directory separators included.

Dim filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                                      TextBox1.Text & " report.pdf")

The function takes a ParamArray argument, so you can provide an arbitrary number of strings to be combined into a single path.

I always try to use methods from System.IO.Path when I'm manipulating file paths. There aren't methods for absolutely everything I've needed to do, but most of the common operations are covered.

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share