[c#] Verify if file exists or not in C#

I am working on an application. That application should get the resume from the users, so that I need a code to verify whether a file exists or not.

I'm using ASP.NET / C#.

This question is related to c# asp.net file-exists

The answer is


You could use:

System.IO.File.Exists(@"c:\temp\test.txt");

Can't comment yet, but I just wanted to disagree/clarify with erikkallen.

You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.

In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().

I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.


You could use:

System.IO.File.Exists(@"c:\temp\test.txt");

To test whether a file exists in .NET, you can use

System.IO.File.Exists (String)

Try this:

     string fileName = "6d294041-34d1-4c66-a04c-261a6d9aee17.jpeg";

     string deletePath= "/images/uploads/";

     if (!string.IsNullOrEmpty(fileName ))
        {
            // Append the name of the file to previous image.
            deletePath += fileName ;

            if (File.Exists(HttpContext.Current.Server.MapPath(deletePath)))
            {
                // deletevprevious image
                File.Delete(HttpContext.Current.Server.MapPath(deletePath));
            }
        }

    if (File.Exists(Server.MapPath("~/Images/associates/" + Html.DisplayFor(modelItem => item.AssociateImage)))) 
      { 
        <img src="~/Images/associates/@Html.DisplayFor(modelItem => item.AssociateImage)"> 
      }
        else 
      { 
        <h5>No image available</h5> 
      }

I did something like this for checking to see if an image existed before displaying it.


You wrote asp.net - are you looking to upload a file?
if so you can use the html

<input type="file" ...


These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.

The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)


Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.

You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.

<asp:FileUpload ID="FileUpload1" runat="server" />

They then pick a file to upload, and you have to deal with any empty file that they might send up server side.


You wrote asp.net - are you looking to upload a file?
if so you can use the html

<input type="file" ...


In addition to using File.Exists(), you might be better off just trying to use the file and catching any exception that is thrown. The file can fail to open because of other things than not existing.


You wrote asp.net - are you looking to upload a file?
if so you can use the html

<input type="file" ...


To test whether a file exists in .NET, you can use

System.IO.File.Exists (String)

Can't comment yet, but I just wanted to disagree/clarify with erikkallen.

You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.

In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().

I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.


You could use:

System.IO.File.Exists(@"c:\temp\test.txt");

These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.

The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)


To test whether a file exists in .NET, you can use

System.IO.File.Exists (String)

This may help you.

try
   {
       con.Open();
       if ((fileUpload1.PostedFile != null) && (fileUpload1.PostedFile.ContentLength > 0))
       {
           filename = System.IO.Path.GetFileName(fileUpload1.PostedFile.FileName);
           ext = System.IO.Path.GetExtension(filename).ToLower();
           string str=@"/Resumes/" + filename;
           saveloc = (Server.MapPath(".") + str);
           string[] exts = { ".doc", ".docx", ".pdf", ".rtf" };
           for (int i = 0; i < exts.Length; i++)
           {
               if (ext == exts[i])
                   fileok = true;
           }
           if (fileok)
           {
               if (File.Exists(saveloc))
                   throw new Exception(Label1.Text="File exists!!!");
               fileUpload1.PostedFile.SaveAs(saveloc);
               cmd = new SqlCommand("insert into candidate values('" + candidatename + "','" + candidatemail + "','" + candidatemobile + "','" + filename + "','" + str + "')", con);
               cmd.ExecuteNonQuery();
               Label1.Text = "Upload Successful!!!";
               Label1.ForeColor = System.Drawing.Color.Blue;
               con.Close();
           }
           else
           {
               Label1.Text = "Upload not successful!!!";
               Label1.ForeColor = System.Drawing.Color.Red;
           }
       }

    }
   catch (Exception ee) { Label1.Text = ee.Message; }

Can't comment yet, but I just wanted to disagree/clarify with erikkallen.

You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.

In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().

I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.


These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.

The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)


In addition to using File.Exists(), you might be better off just trying to use the file and catching any exception that is thrown. The file can fail to open because of other things than not existing.


I have written this code in vb and its is working fine to check weather a file is exists or not for fileupload control. try it

FOR VB CODE ============

    If FileUpload1.HasFile = True Then
        Dim FileExtension As String = System.IO.Path.GetExtension(FileUpload1.FileName)

        If FileExtension.ToLower <> ".jpg" Then
            lblMessage.ForeColor = System.Drawing.Color.Red
            lblMessage.Text = "Please select .jpg image file to upload"
        Else
            Dim FileSize As Integer = FileUpload1.PostedFile.ContentLength

            If FileSize > 1048576 Then
                lblMessage.ForeColor = System.Drawing.Color.Red
                lblMessage.Text = "File size (1MB) exceeded"
            Else
                Dim FileName As String = System.IO.Path.GetFileName(FileUpload1.FileName)

                Dim ServerFileName As String = Server.MapPath("~/Images/Folder1/" + FileName)

                If System.IO.File.Exists(ServerFileName) = False Then
                    FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName)
                    lblMessage.ForeColor = System.Drawing.Color.Green
                    lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully"
                Else
                    lblMessage.ForeColor = System.Drawing.Color.Red
                    lblMessage.Text = "File : " + FileName.ToString() + " already exsist"
                End If
            End If
        End If
    Else
        lblMessage.ForeColor = System.Drawing.Color.Red
        lblMessage.Text = "Please select a file to upload"
    End If

FOR C# CODE ======================

if (FileUpload1.HasFile == true) {
    string FileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);

    if (FileExtension.ToLower != ".jpg") {
        lblMessage.ForeColor = System.Drawing.Color.Red;
        lblMessage.Text = "Please select .jpg image file to upload";
    } else {
        int FileSize = FileUpload1.PostedFile.ContentLength;

        if (FileSize > 1048576) {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "File size (1MB) exceeded";
        } else {
            string FileName = System.IO.Path.GetFileName(FileUpload1.FileName);

            string ServerFileName = Server.MapPath("~/Images/Folder1/" + FileName);

            if (System.IO.File.Exists(ServerFileName) == false) {
                FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName);
                lblMessage.ForeColor = System.Drawing.Color.Green;
                lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully";
            } else {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "File : " + FileName.ToString() + " already exsist";
            }
        }
    }
} else {
    lblMessage.ForeColor = System.Drawing.Color.Red;
    lblMessage.Text = "Please select a file to upload";
}

In addition to using File.Exists(), you might be better off just trying to use the file and catching any exception that is thrown. The file can fail to open because of other things than not existing.


Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.

You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.

<asp:FileUpload ID="FileUpload1" runat="server" />

They then pick a file to upload, and you have to deal with any empty file that they might send up server side.


You can determine whether a specified file exists using the Exists method of the File class in the System.IO namespace:

bool System.IO.File.Exists(string path)

You can find the documentation here on MSDN.

Example:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string resumeFile = @"c:\ResumesArchive\923823.txt";
        string newFile = @"c:\ResumesImport\newResume.txt";
        if (File.Exists(resumeFile))
        {
            File.Copy(resumeFile, newFile);
        }
        else
        {
            Console.WriteLine("Resume file does not exist.");
        }
    }
}

Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.

You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.

<asp:FileUpload ID="FileUpload1" runat="server" />

They then pick a file to upload, and you have to deal with any empty file that they might send up server side.


You can determine whether a specified file exists using the Exists method of the File class in the System.IO namespace:

bool System.IO.File.Exists(string path)

You can find the documentation here on MSDN.

Example:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string resumeFile = @"c:\ResumesArchive\923823.txt";
        string newFile = @"c:\ResumesImport\newResume.txt";
        if (File.Exists(resumeFile))
        {
            File.Copy(resumeFile, newFile);
        }
        else
        {
            Console.WriteLine("Resume file does not exist.");
        }
    }
}

I have written this code in vb and its is working fine to check weather a file is exists or not for fileupload control. try it

FOR VB CODE ============

    If FileUpload1.HasFile = True Then
        Dim FileExtension As String = System.IO.Path.GetExtension(FileUpload1.FileName)

        If FileExtension.ToLower <> ".jpg" Then
            lblMessage.ForeColor = System.Drawing.Color.Red
            lblMessage.Text = "Please select .jpg image file to upload"
        Else
            Dim FileSize As Integer = FileUpload1.PostedFile.ContentLength

            If FileSize > 1048576 Then
                lblMessage.ForeColor = System.Drawing.Color.Red
                lblMessage.Text = "File size (1MB) exceeded"
            Else
                Dim FileName As String = System.IO.Path.GetFileName(FileUpload1.FileName)

                Dim ServerFileName As String = Server.MapPath("~/Images/Folder1/" + FileName)

                If System.IO.File.Exists(ServerFileName) = False Then
                    FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName)
                    lblMessage.ForeColor = System.Drawing.Color.Green
                    lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully"
                Else
                    lblMessage.ForeColor = System.Drawing.Color.Red
                    lblMessage.Text = "File : " + FileName.ToString() + " already exsist"
                End If
            End If
        End If
    Else
        lblMessage.ForeColor = System.Drawing.Color.Red
        lblMessage.Text = "Please select a file to upload"
    End If

FOR C# CODE ======================

if (FileUpload1.HasFile == true) {
    string FileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);

    if (FileExtension.ToLower != ".jpg") {
        lblMessage.ForeColor = System.Drawing.Color.Red;
        lblMessage.Text = "Please select .jpg image file to upload";
    } else {
        int FileSize = FileUpload1.PostedFile.ContentLength;

        if (FileSize > 1048576) {
            lblMessage.ForeColor = System.Drawing.Color.Red;
            lblMessage.Text = "File size (1MB) exceeded";
        } else {
            string FileName = System.IO.Path.GetFileName(FileUpload1.FileName);

            string ServerFileName = Server.MapPath("~/Images/Folder1/" + FileName);

            if (System.IO.File.Exists(ServerFileName) == false) {
                FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName);
                lblMessage.ForeColor = System.Drawing.Color.Green;
                lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully";
            } else {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "File : " + FileName.ToString() + " already exsist";
            }
        }
    }
} else {
    lblMessage.ForeColor = System.Drawing.Color.Red;
    lblMessage.Text = "Please select a file to upload";
}

Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.

You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.

<asp:FileUpload ID="FileUpload1" runat="server" />

They then pick a file to upload, and you have to deal with any empty file that they might send up server side.


You could use:

System.IO.File.Exists(@"c:\temp\test.txt");

    if (File.Exists(Server.MapPath("~/Images/associates/" + Html.DisplayFor(modelItem => item.AssociateImage)))) 
      { 
        <img src="~/Images/associates/@Html.DisplayFor(modelItem => item.AssociateImage)"> 
      }
        else 
      { 
        <h5>No image available</h5> 
      }

I did something like this for checking to see if an image existed before displaying it.


You can determine whether a specified file exists using the Exists method of the File class in the System.IO namespace:

bool System.IO.File.Exists(string path)

You can find the documentation here on MSDN.

Example:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string resumeFile = @"c:\ResumesArchive\923823.txt";
        string newFile = @"c:\ResumesImport\newResume.txt";
        if (File.Exists(resumeFile))
        {
            File.Copy(resumeFile, newFile);
        }
        else
        {
            Console.WriteLine("Resume file does not exist.");
        }
    }
}

In addition to using File.Exists(), you might be better off just trying to use the file and catching any exception that is thrown. The file can fail to open because of other things than not existing.


This may help you.

try
   {
       con.Open();
       if ((fileUpload1.PostedFile != null) && (fileUpload1.PostedFile.ContentLength > 0))
       {
           filename = System.IO.Path.GetFileName(fileUpload1.PostedFile.FileName);
           ext = System.IO.Path.GetExtension(filename).ToLower();
           string str=@"/Resumes/" + filename;
           saveloc = (Server.MapPath(".") + str);
           string[] exts = { ".doc", ".docx", ".pdf", ".rtf" };
           for (int i = 0; i < exts.Length; i++)
           {
               if (ext == exts[i])
                   fileok = true;
           }
           if (fileok)
           {
               if (File.Exists(saveloc))
                   throw new Exception(Label1.Text="File exists!!!");
               fileUpload1.PostedFile.SaveAs(saveloc);
               cmd = new SqlCommand("insert into candidate values('" + candidatename + "','" + candidatemail + "','" + candidatemobile + "','" + filename + "','" + str + "')", con);
               cmd.ExecuteNonQuery();
               Label1.Text = "Upload Successful!!!";
               Label1.ForeColor = System.Drawing.Color.Blue;
               con.Close();
           }
           else
           {
               Label1.Text = "Upload not successful!!!";
               Label1.ForeColor = System.Drawing.Color.Red;
           }
       }

    }
   catch (Exception ee) { Label1.Text = ee.Message; }

To test whether a file exists in .NET, you can use

System.IO.File.Exists (String)

You can determine whether a specified file exists using the Exists method of the File class in the System.IO namespace:

bool System.IO.File.Exists(string path)

You can find the documentation here on MSDN.

Example:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string resumeFile = @"c:\ResumesArchive\923823.txt";
        string newFile = @"c:\ResumesImport\newResume.txt";
        if (File.Exists(resumeFile))
        {
            File.Copy(resumeFile, newFile);
        }
        else
        {
            Console.WriteLine("Resume file does not exist.");
        }
    }
}

You wrote asp.net - are you looking to upload a file?
if so you can use the html

<input type="file" ...


Try this:

     string fileName = "6d294041-34d1-4c66-a04c-261a6d9aee17.jpeg";

     string deletePath= "/images/uploads/";

     if (!string.IsNullOrEmpty(fileName ))
        {
            // Append the name of the file to previous image.
            deletePath += fileName ;

            if (File.Exists(HttpContext.Current.Server.MapPath(deletePath)))
            {
                // deletevprevious image
                File.Delete(HttpContext.Current.Server.MapPath(deletePath));
            }
        }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to file-exists

Portable way to check if directory exists [Windows/Linux, C] VBA check if file exists How to check if a file exists from a url check if file exists in php How do I check if a file exists in Java? Verify if file exists or not in C# How do I check whether a file exists without exceptions? Deleting a file in VBA