1

I have found this code while I was busy searching for an answer!

private void btnOpenFile_Click(object sender, EventArgs e)
{
    OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
    saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
    saveFileDialogBrowse.Title = "Save an pcap File";
    saveFileDialogBrowse.ShowDialog();
    var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename

    if (pcapFile != "")
    {
        FileInfo fileInfo = new FileInfo(pcapFile);
        txtFilePath.Text = fileInfo.FullName;
    }
}
Andy Wilkinson
  • 97,688
  • 22
  • 237
  • 223
net
  • 11
  • 2

3 Answers3

2

There is no easy way.

You can use File.Exists to check for file existence on the path, but a change can still happen before the execution of the next line. Your best option is to combine File.Exists with try-catch to catch any possible exceptions.

private void btnOpenFile_Click(object sender, EventArgs e)
{
    OpenFileDialog saveFileDialogBrowse = new OpenFileDialog();
    saveFileDialogBrowse.Filter = "Pcap file|*.pcap";
    saveFileDialogBrowse.Title = "Save an pcap File";
    saveFileDialogBrowse.ShowDialog();
    var pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename
    try
    {
        if (File.Exists(pcapFile))
        {
            FileInfo fileInfo = new FileInfo(pcapFile);
            txtFilePath.Text = fileInfo.FullName;
        }
    }
    catch (FileNotFoundException fileNotFoundException)
    {
        //Log and handle
    }
    catch (Exception ex)
    {
        //log and handle
    }
}
Habib
  • 212,447
  • 27
  • 392
  • 421
1

You can use the File.Exists method:

string fullPath = @"c:\temp\test.txt";
bool fileExists = File.Exists(fullPath);
Abbas
  • 13,778
  • 6
  • 40
  • 69
1

You can use the File.Exists method, which is documented here.

Codor
  • 17,235
  • 9
  • 32
  • 52