user1710944
user1710944

Reputation: 1459

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

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;
    }
}

Upvotes: 3

Views: 3202

Answers (3)

Ravindra Bagale
Ravindra Bagale

Reputation: 17675

use the FileInfo constructor.

It will throw a ArgumentException if The file name is empty, contains only white spaces, or contains invalid characters. It can also throw SecurityException

or use Path.GetInvalidPathChars Method

it Gets an array containing the characters that are not allowed in path names.

// Get a list of invalid file characters.

char[] invalidFileChars = Path.GetInvalidFileNameChars();

Upvotes: 0

lumberjack4
lumberjack4

Reputation: 2872

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.

Upvotes: 4

petro.sidlovskyy
petro.sidlovskyy

Reputation: 5103

Please use File.Exists method. It won't throw an exception. From MSDN:

true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. This method also returns false if path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path.

Upvotes: 9

Related Questions