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.N
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)
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; }
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.
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.
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.