27

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#.

  • 1
    @suresh -- on StackOverflow when you see an answer that you think adequately answers your query and is the best one that does, you should honors it properly... – Hardryv Aug 03 '11 at 12:36
  • 1
    I think this question actually is - _"How can I know the file uploaded by a user from a web form already exists on the server."_ not sure why it got 8 upvotes. – Burhan Khalid Jul 31 '12 at 13:44

12 Answers12

66

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.");
        }
    }
}
splattne
  • 102,760
  • 52
  • 202
  • 249
  • how can i get the selected file path.. ? –  Jan 06 '09 at 10:18
  • 1
    What do you mean by "selected path"? There is Server.MapPath(SOME_VIRTUAL_PATH). See here: http://stackoverflow.com/questions/275781/server-mappath-server-mappath-server-mappath-server-mappath-what#275791 – splattne Jan 06 '09 at 10:34
  • @suresh -- in .NET it's easiest to always work with full file path strings. There is a static .NET class at System.IO.Path you can use to tear apart a FilePath string if needed (for extension, directory, and filename components, etc.) and it's aware of how Microsoft applications handle file operations. splattne's answer takes care of your original question... I recommend you 'accept his answer'. As to your follow on question above-- 'how to get a selected file path'... see my next entry. – Hardryv Nov 21 '11 at 16:29
  • @suresh -- When you ask how to 'get the selected file path' that question seems to imply that you know where one is and that its in fact selected, possibly within a control in an application you're working on such as the drop-down-list of a ComboBox. If that's what you meant you need to be more specific -- there are so many different paradigms. StackOverflow has a myriad of very technical users and we're all peers... please be precise, reread before posting, and verify that your question is understandable. Also make sure we know what you're seeking so we can provide it to you. – Hardryv Nov 21 '11 at 16:34
  • Didn't realize the the '@' before the filename converts the single slash to double slashes; I always was using double slashes. Thanks! – Jim Lahman Aug 23 '12 at 14:12
  • 1
    @JimLahman actually, it's the other way round: normal C# strings are escaped, which means that e. g. \n will become a line break. With @ strings are interpreted as not-escaped (\n will be printed as \ and n) – splattne Aug 23 '12 at 21:11
14

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

System.IO.File.Exists (String)
bluish
  • 26,356
  • 27
  • 122
  • 180
James Ogden
  • 852
  • 6
  • 11
9
    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.

Eric Bishard
  • 5,201
  • 7
  • 51
  • 75
4

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));
            }
        }
Jmocke
  • 269
  • 1
  • 10
  • 20
3

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.

Keith
  • 150,284
  • 78
  • 298
  • 434
2

You could use:

System.IO.File.Exists(@"c:\temp\test.txt");
Ruben
  • 6,367
  • 1
  • 24
  • 35
2

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.

Community
  • 1
  • 1
Todd Friedlich
  • 662
  • 1
  • 5
  • 13
  • I'm absolutely agree with you! But if you look at some frameworks like .Net or Java one tends to believe that it's planned to use exceptions as normal program flow stuff (I don't know how the poor performance fits in that concept!) – mmmmmmmm Jan 06 '09 at 12:49
1

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.

bluish
  • 26,356
  • 27
  • 122
  • 180
erikkallen
  • 33,800
  • 13
  • 85
  • 120
1

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)

ZombieSheep
  • 29,603
  • 12
  • 67
  • 114
1

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

<input type="file" ...

Dror
  • 7,255
  • 3
  • 38
  • 44
0

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

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";
}
manishN
  • 1
  • 1