Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
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:

Desktop0001report.pdf

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

        Try
            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)
            pdfdoc.Open()
            FillPDF(pdfdoc)
            pdfdoc.Close()
            Process.Start(filename)


        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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...