Topic: Validating File Exists - File IO
Share/Save/Bookmark
Note: Needs System.IO Class
 
Private Function ValidateFile(ByVal theFile As String, ByVal FilePath As String, ByRef ErrorMessage As StringBuilder) As Boolean
        Dim fileValid As Boolean = False
        Dim folder As New IO.DirectoryInfo(FilePath)
        Dim files As IO.FileInfo() = folder.GetFiles()
        Try
 
            If File.Exists(FilePath & "\" & theFile) Then
                Try
                    ' Use this instead of Setting acces time incase the file is password protected
                    File.SetAttributes(FilePath & "\" & theFile, FileAttributes.ReadOnly)
                    File.SetAttributes(FilePath & "\" & theFile, FileAttributes.Normal)
                    fileValid = True
                Catch
                    ErrorMessage.AppendLine(theFile & " is currently opened.")
                End Try
            Else
                ErrorMessage.AppendLine(theFile & " does not exist in directory.")
            End If
 
            Return fileValid
 
        Catch ex As Exception
            Throw
        Finally
            folder = Nothing
            files = Nothing
        End Try
 
    End Function
 
C# Folder/Directory & File
                if (radioDirectory.Checked)
                {
                    if (!System.IO.Directory.Exists(txtDirectory.Text.Trim()))
                    {
                        sb.AppendLine("The directory path does not exist or device is not ready.");
                        lblDirectory.ForeColor = Color.Red;
                        btnNoDirectory.Visible = true;
                        Validation = false;
                    }
                }
                else // File
                {
                    if (!System.IO.File.Exists(txtDirectory.Text.Trim()))
                    {
                        sb.AppendLine("The file does not exist.");
                        lblDirectory.ForeColor = Color.Red;
                        btnNoDirectory.Visible = true;
                        Validation = false;
                    }
                }