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#.
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.");
}
}
}
To test whether a file exists in .NET, you can use
System.IO.File.Exists (String)
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.
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));
}
}
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");
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)
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.
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; }
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";
}
Related
I try to download a file and to be able to choose its locationenter image description here
Here is the code I made
in "use of the directory", that's where I define a directory, but I want to be able to choose it via "FolderbrowserDialog"
Please refer to the example here: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.folderbrowserdialog?view=netframework-4.7.2
Specifically:
if(result == DialogResult.OK)
{
openFileName = openFileDialog1.FileName;
try
{
// Output the requested file in richTextBox1.
Stream s = openFileDialog1.OpenFile();
richTextBox1.LoadFile(s, RichTextBoxStreamType.RichText);
s.Close();
fileOpened = true;
}
catch(Exception exp)
{
MessageBox.Show("An error occurred while attempting to load the file. The error is:"
+ System.Environment.NewLine + exp.ToString() + System.Environment.NewLine);
fileOpened = false;
}
I need to upload a CSV file to an ASP.NET application, on an Azure server. Although it works fine on my local machine, when uploading it to the server the following error is thrown:
"Process cannot access the file
'C:\inetpub\wwwroot\ImportFiles\9_11.csv' because it is being used by
another process"
My code:
string fileName = DateTime.Now.ToString().Replace(':', '_').Replace('/', '_').Replace(' ', '_') + Convert.ToString((new Random()).Next(0, 999) * (new Random()).Next(0, 999));
string path = Server.MapPath("ImportFiles") + "\\" + fileName + "" + FileImport.FileName.Substring(FileImport.FileName.IndexOf('.'));
FileImport.SaveAs(path);
string pathforSeconStream = path;
try
{
Response.Write("<script> alert('In Try Block');</script>");
bool flag = true;
int visiblemessageCount = 0;
int rollNo = 1;
StreamReader ColLine = new StreamReader(path);
string ColInputline = ColLine.ReadLine();
String[] ColsInput = ColInputline.Split(',');
ColLine.Close();
ColLine.Dispose();
string preFix = "", RollNumber = "";
StreamReader sr = new StreamReader(pathforSeconStream);
}
catch(Exception ex)
{
}
The code to generate a unique filename is wrong. Use Path.GetTempFileName.
PS never eat an exceptiion. Please remove catch (Exception ex) {};
Revision
Instead of FileImport.Save(...) just save the request in a MemoryStream and then work on it.
I am using the following code to export a crystal report in pdf format.
if (textBox1.Text == "" | textBox2.Text == "")
{
}
else
{
string filename = "\\" + textBox1.Text + ".pdf";
CreateEmptyFile(filename);
string file = textBox2.Text + "\\" + textBox1.Text + ".pdf";
labelget();
try
{
int idx = dataGridView1.CurrentCell.RowIndex;
string parv = dataGridView1.Rows[idx].Cells[0].FormattedValue.ToString();
ReportDocument wordreport = new ReportDocument();
wordreport.Load(#"C:\\FOLDER\\TESTREPORT.rpt");
wordreport.SetDatabaseLogon("root", "xxxxxxx", localhost, database);
wordreport.Refresh();
wordreport.SetParameterValue("bill_no", parv);
wordreport.SetParameterValue("fromterminal", this.terminal);
wordreport.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, file);
}
catch (Exception em)
{
MessageBox.Show("error is: " + em);
}
}
Error Occurs in line wordreport.ExportToDisk saying the system could not find the specified path. I checked the permissions for the path where I created the PDF file, It all looks good.
How do i rectify this error?
I Found the Reason and answer for my question. I missed to add DSN details in admin tools.
I want to limit the types of files that are uploaded to my site. Im using this function below. Would I write if statements for .jpg || .gif || .jpeg || .png.
I don't want people uploading exe's. What is the best way to do this?
if (FileUpload1.HasFile)
try
{
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
var Myguid = Guid.NewGuid().ToString("N");
//Check to make sure its an allowable file to be uploaded???????????
var newName = Guid.NewGuid() + FileExtension;
//Map path to folder
string realpath = Server.MapPath("Pictures\\") + newName;
//FileUpload1.SaveAs("C:\\Users\\josh\\Desktop\\JaysVersion\\PicRatingSite\\PicRatingSite\\Pictures" + FileUpload1.FileName);
FileUpload1.SaveAs(realpath);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
InsertMembers insert = new InsertMembers();
int age = Int32.Parse(txtAge.Text);
insert.InsertNewMember(txtEmail.Text, Myguid, txtName.Text, txtCity.Text, txtState.Text, txtDescription.Text, age, gender);
//Get Member Id to Insert into Pictures table
GetMemberInfo GetID = new GetMemberInfo();
int UMemberId = GetID.GetMemberId(Myguid);
Displayme.Text = newName.ToString();
//Now that i have member Id Lets insert new picture into picture table
Picture InsertnewPictures = new Picture();
int insertpics = InsertnewPictures.InserNewPicture(UMemberId, newName, 0);
}
catch (Exception ex)
{
//Handle the error
throw ex;
}
else
{
Label1.Text = "You have not specified a file.";
}
Do NOT trust the filename the user provides. It's trivial to hack, and someone can easily do "rename nastyvirus.exe cutekittens.jpg" prior to upload. You must user server-side mime type detection to ensure that you really did get an image. Same goes for the MIME type provided by the remote browser. It can also be trivially forged and make "nastyvirus.exe" show up as "text/plain".
you can filter the type of the file to be upload using a switch statement
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch(FileExtension.ToLower())
{
case".jpg":
case".png":
case".gif":
case".jpeg":
break;
default:
Response.Write("this file type is not allowed");
return;
}
I'm trying to upload a file and change its name below. I need to get the file extension. The code below has a underline under "Path" am I missing a using statement? Or what is the correct syntax for what I'm doing?
if (FileUpload1.HasFile)
try
{
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
var newName = DateTime.Now.ToLongDateString();
//Map path to folder
string realpath = Server.MapPath("Pictures\\") + Guid.NewGuid() + FileExtension;
FileUpload1.SaveAs(realpath);
Label1.Text = "File name: " +
FileUpload1.PostedFile.FileName + "<br>" +
FileUpload1.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload1.PostedFile.ContentType;
}
catch (Exception ex)
{
//Handle the error
throw ex;
}
else
{
Label1.Text = "You have not specified a file.";
}
FileInfo fi = new FileInfo(fileName);
string ext = fi.Extension;
"Path" am I missing a using statement?
You have to add
using System.IO;
to the list of namespaces
The code you have provided looks fine (and works on my machine).
The only thing I can see that you might be missing is the using statement for System.IO.
Use this code:
string extension=System.IO.Path.GetExtension(file1.FileName);