Determine via C# whether a File Path is valid and exists

c#, path, validation, winforms

Solution

`FileInfo` will throw an exception if the path provided to it is malformed. If you want to know if that file already exists check the `FileInfo.Exists` property.

Problem

I am building a WinForms application that receives a path from a user via a `SaveFileDialog`. Here is the relevant portion of my code. How can I determine if the path `pcapFile` is valid and exists? ``` private void btnBrowse_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialogBrowse = new SaveFileDialog(); saveFileDialogBrowse.Filter = "Pcap file|*.pcap"; saveFileDialogBrowse.Title = "Save an pcap File"; saveFileDialogBrowse.ShowDialog(); pcapFile = saveFileDialogBrowse.FileName; //do whatever you like with the selected filename if (pcapFile != "") { FileInfo fileInfo = new FileInfo(pcapFile); tbOutputFileName.Text = fileInfo.FullName; } } ```

Original source