Hello I have a method in my controller that looks like this.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadImage(int? id)
{
if (id == null)
return HttpNotFound();
Component c = db.Components.Find((int)id);
HttpPostedFileBase photo = Request.Files["image"];
if (photo != null && photo.ContentLength > 0)
{
var filename = IGT.imagePath + "\\Components\\" + id.ToString() + ".jpg";
photo.SaveAs(filename);
c.Image_Url = IGT.baseUrl + "/Content/images/Components/" + id.ToString() + ".jpg";
db.SaveChanges();
}
else
{
if (Request["imageurl"] != null && Request["imageurl"].Length > 0)
{
// download this file
WebClient wc = new WebClient();
wc.DownloadFile(Request["imageurl"], IGT.imagePath + "\\Components\\" + id.ToString() + ".jpg");
c.Image_Url = IGT.baseUrl + "/Content/images/Components/" + id.ToString() + ".jpg";
db.SaveChanges();
}
}
HttpPostedFileBase reference = Request.Files["referencefile"];
if (reference != null && reference.ContentLength > 0)
{
// Upload the origin file and create a URL
var filename = IGT.contentPath + "\\uploads\\Comp-" + id.ToString() + "-" + System.IO.Path.GetFileName(reference.FileName);
reference.SaveAs(filename);
c.Reference_Url = IGT.baseUrl + "/Content/uploads/Comp-" + id.ToString() + "-" + System.IO.Path.GetFileName(reference.FileName);
db.SaveChanges();
}
return RedirectToAction("Edit", new { id = id });
}
But currently when it gets to
photo.SaveAs(filename);
I receive the error message
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Users\chris\Source\Repos\inventory2.0\PIC_Program_1.0\Content\images\Components\498.jpg
How can I make a try catch block so that if the folder doesn't exist in IIS Express, it will create it?
You could use the below code to create directory programmatically:
if (!Directory.Exists(appDataPath)) {
Directory.CreateDirectory(appDataPath);
}
and use directory.SetAccessControl(security); method to set the permission to that folder.
please refer the below links for more detail:
https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.createdirectory?view=netframework-4.8
C# Creating directory and setting the permissions
https://www.kunal-chowdhury.com/2016/02/folder-permission.html
Can you try this code:
if (!System.IO.Directory.Exists("your folder")) {
System.IO.Directory.CreateDirectory("Your Folder");
}
Also, make sure your IIS user has a read/write access to that folder directory.
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;
}
im using a file upload control and here is my code :
//Uploading the image
if (imageUpload.HasFile)
{
try
{
if (imageUpload.PostedFile.ContentType == "image/jpeg")
{
if (imageUpload.PostedFile.ContentLength < 102400)
{
string im = ( "~/User" + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".jpeg");
imageUpload.SaveAs(im);
uploadLabel.Text = "";
}
else
{
uploadLabel.Text = "File size must be less than 1024 kb";
}
}
else
{
uploadLabel.Text = "File must be in jpeg/jpg format";
}
}
catch(Exception ex)
{
uploadLabel.Text = "File upload failed becuase: " + ex.Message;
}
}
but im getting an error:
The SaveAs method is configured to require a rooted path, and the path "path" is not rooted.
what am i doing wrong.
thanks
SaveAs() requires an absolute path.
try using Request.PhysicalApplicationPath + "\\User"
The Save method is configured to require an absolute path (starting with X:\..., in some drive).
You should call Server.MapPath to get the absolute path on disk to ~/whatever.
Add Server.MapPath where you declare im
Server.MapPath gives you the absolute path.
string im = Server.MapPath("/User") + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".jpeg";
string filename = FileUpload1.FileName.ToString();
if (filename != "")
{
ImageName = FileUpload1.FileName.ToString();
ImagePath = Server.MapPath("Images");
SaveLocation = ImagePath + "\\" + ImageName;
SaveLocation1 = "~/Image/" + ImageName;
sl1 = "Images/" + ImageName;
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
try this may be help ful.......
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";
}