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
  • 108,729
  • 24
  • 257
  • 242
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
  • 219,104
  • 29
  • 407
  • 436
1

You can use the File.Exists method:

string fullPath = @"c:\temp\test.txt";
bool fileExists = File.Exists(fullPath);
Abbas
  • 14,186
  • 6
  • 41
  • 72
1

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

Codor
  • 17,447
  • 9
  • 29
  • 56