In this article I will explain with an example, how to upload file to Folder (Directory) in Windows Forms (WinForms) Application using C# and VB.Net.
Form Design
The following Windows Form consists of a Button and a Label control.
Namespaces
You will need to import the following namespace.
C#
VB.Net
Uploading File with the OpenFileDialog Box
The following event handler gets called, when the Select File Button is clicked.
Then, the directory will be checked whether exists or not, if directory doesn’t exist then Folder (Directory) will be created.
Next, the Path of the selected File is read from the FileName property of the OpenFileDialog Box and copied to the Folder (Directory) using Copy method of File class.
Finally, a success message is displayed in the Label.
C#
private void btnSelect_Click(object sender, EventArgs e)
{
string saveDirectory = @"E:\Files";
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (!Directory.Exists(saveDirectory))
{
Directory.CreateDirectory(saveDirectory);
}
string fileName = Path.GetFileName(openFileDialog1.FileName);
string fileSavePath = Path.Combine(saveDirectory, fileName);
File.Copy(openFileDialog1.FileName, fileSavePath, true);
lblMessage.Text = "File uploaded Successfully.";
}
}
}
VB.Net
Private Sub btnSelect_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSelect.Click
Dim saveDirectory As String = "E:\Files"
Using openFileDialog1 As OpenFileDialog = New OpenFileDialog()
If openFileDialog1.ShowDialog() = DialogResult.OK Then
If Not Directory.Exists(saveDirectory) Then
Directory.CreateDirectory(saveDirectory)
End If
Dim fileName As String = Path.GetFileName(openFileDialog1.FileName)
Dim fileSavePath As String = Path.Combine(saveDirectory, fileName)
File.Copy(openFileDialog1.FileName, fileSavePath, True)
lblmessage.Text = "File uploaded Successfully."
End If
End Using
End Sub
Screenshot
Demo
Downloads