Display (Open) file from path stored in project folder (directory) in Windows Application

Last Reply 6 months ago By arunkurmi

Posted 6 months ago

I store a file in project folder I need to view file on clicking datagriview file .

Posted 6 months ago

Hi gokuldas,

Check this sample now. please take its reference

Namespaces

C#

using System.Data;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

VB.Net

Imports System.Data
Imports System.Diagnostics
Imports System.IO
Imports System.Windows.Forms

Code

C#

private void Form1_Load(object sender, EventArgs e)
{
    string path = Application.StartupPath.Replace("bin\\Debug", "Files");
    string[] files = Directory.GetFiles(path);
    DataTable dt = new DataTable();
    dt.Columns.Add("Path");
    dt.Columns.Add("FileName");
    foreach (string file in files)
    {
        string fileName = Path.GetFileName(file);
        dt.Rows.Add(fileName, file);
    }
    dataGridView1.DataSource = dt;
    DataGridViewButtonColumn btnView = new DataGridViewButtonColumn();
    btnView.HeaderText = "View File";
    btnView.Text = "View";
    btnView.UseColumnTextForButtonValue = true;
    btnView.Width = 80;
    dataGridView1.Columns.Add(btnView);
    dataGridView1.CellContentClick += new DataGridViewCellEventHandler(ViewFile);
}

private void ViewFile(object sender, DataGridViewCellEventArgs e)
{
    string fileName = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
    Process myProcess = new Process();
    myProcess.StartInfo.FileName = fileName;
    myProcess.Start();
}

VB.Net

Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim path As String = Application.StartupPath.Replace("bin\Debug", "Files")
    Dim files As String() = Directory.GetFiles(path)
    Dim dt As DataTable = New DataTable()
    dt.Columns.Add("Path")
    dt.Columns.Add("FileName")
    For Each file As String In files
        Dim fileName As String = System.IO.Path.GetFileName(file)
        dt.Rows.Add(fileName, file)
    Next
    dataGridView1.DataSource = dt
    Dim btnView As DataGridViewButtonColumn = New DataGridViewButtonColumn()
    btnView.HeaderText = "View File"
    btnView.Text = "View"
    btnView.UseColumnTextForButtonValue = True
    btnView.Width = 80
    dataGridView1.Columns.Add(btnView)
    AddHandler dataGridView1.CellContentClick, AddressOf Me.ViewFile
End Sub

Private Sub ViewFile(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
    Dim fileName As String = dataGridView1.Rows(e.RowIndex).Cells(1).Value.ToString()
    Dim myProcess As Process = New Process()
    myProcess.StartInfo.FileName = fileName
    myProcess.Start()
End Sub

Screenshot