Cannot display images using path created Server.MapPath - c#

I am trying display images on the webpage from the folder placed in my project root directory. The path that I am storing in the database is as follows:
D:\Projects\OnlineStore\OnlineStore\OnlineStore\Content\Uploads\Images\Bundles\706976d31e274e7ab36986b9bec2f0f9-Object
Image.jpg
The code that generated this path is as follows:
var path = Path.Combine(Server.MapPath("~/Content/Uploads/Images/Bundles"), fileId);
photo.SaveAs(path);
Image doesn't show using this path. The path that works is as follows:
\Content\Uploads\Images\Bundles\706976d31e274e7ab36986b9bec2f0f9-Object
Image.jpg
How do I resolve this issue? I was thinking about using first path to save image file to folder and save second path in the database. But this doesn't seem the right way of doing this.

1. Only store FileName in database Check this.
string fileName = System.IO.Path.GetFileName(file.FileName);
//store fileName in your ImageName column of Image your Image table
//Note: generate unique filename using `Guid` or `PrimaryKey` to overcome
//same file name issue.
2. Use #Url.Content to show image in view.
<img src="#Url.Content("~")/Content/Uploads/Images/Bundles/#Model.ImageName"/>
Reference

In controller:
public ActionResult UserRegister(Register Register)
{
try
{
DbConnection dbHandle = new DbConnection();
dbHandle.Connection();
using (SqlCommand UserRegistercmd = new SqlCommand("USPUserRegistration", dbHandle.con))
{
DateTime dob = Convert.ToDateTime(Register.dateOfBirth);
string Random = System.DateTime.Now.ToString("ddMMyyhhmmss");
Register.UserPhoto = "../Images/" + Random + Register.userImg.FileName;
Register.userImg.SaveAs(Server.MapPath("../Images/") + Random + Register.userImg.FileName);
UserRegistercmd.CommandType = CommandType.StoredProcedure;
dbHandle.con.Open();
UserRegistercmd.ExecuteNonQuery();
dbHandle.con.Close();
ViewBag.error = "Company Registration Sucess";
Mail.SendMail(Register.email,"Your User Name and Password ","User Name :"+Register.username+"Paassword :"+Register.password);
}
}
catch (Exception e)
{
ViewBag.error = "Error!!";
ExceptionLog.Log(e, Request.UserHostAddress);
return RedirectToAction("Error_View", "CompanyRegister");
}
finally
{
Dispose();
}
return RedirectToAction();
}
in cshtml use #Url.Content:
<img src="#Url.Content(#Model.UserPhoto)" alt="There is no Image" style="height:150px;width:150px" onclick="ChangeImg()" />

Related

My controller couldnt save physical file path in production

I tried to update file to physically via my controller. But my controller save in local (actually Visual Studio run) perfectly but when I tried to publish and setup to on my server and use www.mywebsite.com then controller couldn't save to path without an error.
My scenerio is like this:
In client side onReady js method, I get physical root path from my database (this is work both side, no problem i watching debug console). My physical path like this: \\192.168.1.1\MYFILE-1.1
I pass to value with POST method file and root path via Model
In a controller side, I create timestamp for a file name, and combine more path file. Like this my controller:
[HttpPost]
public JsonResult SavePhysicalPath(FileModel model)
{
//create timestamp of file name
string filesMimeType = MimeTypesMap.GetMimeType(model.FormFile.FileName);
string filesExtType = MimeTypesMap.GetExtension(filesMimeType);
string fnTimeStamp = DateTime.Now.ToString("ddMMyyyy_HHmmssffff");
string edittedFileName = fnTimeStamp + "." + filesExtType;
string edittedFmAndSubPath = "MyDocs\\OtherFiles\\" +edittedFileName ;
var savingRootPath = "";
savingRootPath =model.FileFolderPath; // FileFolderPath is string get from view "\\192.168.1.1\MYFILE-1.1"
try
{
string SavePath = Path.Combine(Directory.GetCurrentDirectory(), savingRootPath, edittedFmAndSubPath );
using (var stream = new FileStream(SavePath, FileMode.Create))
{
model.FormFile.CopyTo(stream);
}
stringOutput = "OK";
return Json(stringOutput);
}
catch (Exception ex)
{
stringOutput = "ERR";
return Json(stringOutput);
throw;
}
}
if there is no directory, then create one.
bool exists = System.IO.Directory.Exists(SavePath);
if (!exists)
System.IO.Directory.CreateDirectory(SavePath);
or you can create one in manually on server.

File upload path not saving right

I am using the following code to save my file into database using entity framework But for some reason it is giving me the error:
'C:/Users/David Buckley/Documents/Visual Studio 2012/Sis/StudentInformationSystem/admin/uploads/' is a physical path, but a virtual path was expected.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: 'C:/Users/David Buckley/Documents/Visual Studio 2012/Sis/StudentInformationSystem/admin/uploads/' is a physical path, but a virtual path was expected
But it seems to save the file ok in database as the path and filename of C:\Users\David Buckley\Documents\Visual Studio 2012\Sis\StudentInformationSystem\admin\uploads\test.jpg which exsits but i persume I need to save it differently if I want to load it into an image control imageurl field property?.
try
{
int id = Convert.ToInt32(Request.QueryString["id"]);
if (id == -1) // we neeed a new record otherwise get the old one;
{
Student studentRecord = new Student();
_db.AddStudent(studentRecord);
_db.SaveChanges();
newRecordId = studentRecord.Student_ID;
Session["recordid"] = id;
_student = _db.GetStudentById(newRecordId);
}else
_student = _db.GetStudentById(id);
photoUpload.TargetFolder= Server.MapPath("~/admin/uploads/");
string fullPath = Server.MapPath( "~/admin/uploads/");
photoUpload.OverwriteExistingFiles = true;
string newFileName = "";
foreach (UploadedFile file in photoUpload.UploadedFiles)
{
string fileName = "test";
newFileName =fileName + file.GetExtension();
file.SaveAs(Path.Combine(fullPath, newFileName));
// impelement your database insert here...
}
string thumbPath;
thumbPath = ("~/images" + "/" + newFileName);
_student.Image = thumbPath;
_student.Student_Name = txtStudentName.Text;
_student.Student_FatherName = txtFathersName.Text;
_student.Registration_no = txtRegistrationNo.Text;
_student.Address1 = txtAddress1.Text.Trim();
_student.Address2 = txtAddress2.Text.Trim();
_student.Address3 = txtAddress3.Text.Trim();
_student.RelationWithGuadian = txtRelationshipGurdan.Text.Trim();
_student.GurdianName = txtGurdianName.Text.Trim();
_student.LastSchoolAtten = txtLastSchool.Text.Trim();
_student.Contact1 = txtContact1.Text.Trim();
_student.Contact2 = txtContact2.Text.Trim();
_student.DOB = rdDOB.SelectedDate.Value;
_db.SaveChanges();
}
catch (Exception ex)
{
}
To access the file from a web application, you will need to use a virtual path. But you are saving a physical path to the file in the database. Instead of saving the value of Path.Combine(fullPath, newFileName) in the database, you should be saving the value of "~/admin/uploads/" + newFileName.
The above works as long as your uploads/ directory is a descendant of your application directory. Alternatively, you can use a path that points to a directory outside of your application path by explicitly adding a virtual directory.
How to add a virtual directory in IIS express
How to add a virtual directory in IIS

Upload multiple files & create zip

I managed to upload two kinds of files successfully & store the respective filepaths on the database. Now,I'd also like to create a zip with both files attached to it.
I referenced the codes to this particular webpage regarding zip files & file uploads
http://www.c-sharpcorner.com/uploadfile/5089e0/how-to-create-zip-in-asp-net-using-c-sharp/
Upon clicking the submit button, a File Not Found exception is thrown.
An exception of type 'System.IO.FileNotFoundException' occurred in Ionic.Zip.dll but was not handled in user code
Additional information: C:\Users\seldarine\Desktop\Proj\PP_PJ\PP_Project\SFiles\Submissions\blueteam\MyCodesF.zip
The exception is thrown at this particular line - objZip.Save(Path.Combine(serverFilePath,zipName));
Here are a portion of my codes :
protected void btn_submit_Click(object sender, EventArgs e)
{
string input = "";
string pp, vv,zip;
string extPp, extVv;
if (f_slide.HasFile && f_video.HasFile)
{
//Get file name & extensions
pp = Path.GetFileName(f_slide.PostedFile.FileName);
extPp = Path.GetExtension(pp);
vv = Path.GetFileName(f_video.PostedFile.FileName);
extVv = Path.GetExtension(vv);
string user = Session["userid"].ToString();
//where zip name is named after the username (current user) logged in
string zipName = user + ".zip";
//To save to folders
string filePath = "SFiles/Submissions/" + user + "/";
string serverFilePath = Server.MapPath(filePath);
//If directory does not exist
if (!Directory.Exists(serverFilePath))
{ // if it doesn't exist, create
System.IO.Directory.CreateDirectory(serverFilePath);
}
//****To create zip file*****
using(ZipFile objZip = new ZipFile())
{
string zipSlidePath = Path.Combine(serverFilePath,pp);
string zipVideoPath = Path.Combine(serverFilePath,vv);
objZip.AddFile(zipSlidePath);
objZip.AddFile(zipVideoPath);
***objZip.Save(Path.Combine(serverFilePath,zipName));***
}
//Store files
f_slides.SaveAs(Path.Combine(serverFilePath, pp));
f_video.SaveAs(Path.Combine(serverFilePath, vv));
.....
Try adding another line above the crashing one and see if you can debug it and what result you get:
var savePath = Path.Combine(serverFilePath,zipName +".zip");
You might also want to try changing the savePath variable to something like c:\temp\test.zip and see if that works.
var savePath = "c:\\temp\\test.zip";
Make sure the user under which the server is running has write access to that folder (serverFilePath).

Error Access to the path is denied when Rename a Directory

I want to rename the a folder with the new name inputed in a Textbox txtFilenFolderName:
protected void btnUpdate_Click(object sender, EventArgs e)
{
string[] values = EditValue;
string oldpath = values[0];// = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder"
string oldName = values[2]; //= New Folder
string newName = txtFilenFolderName.Text; //= New Folder1
string newPath = string.Empty;
if (oldName != newName)
{
newPath = oldpath.Replace(oldName, newName);
Directory.Move(oldpath, newPath);
}
else
lblmessage2.Text = "New name must not be the same as the old ";
}
}
Try to debug:
oldpath = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder"
oldName = New Folder
newName= New Folder1
newpath = "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder1"
Everything seems right, but I when I click on buton Edit ---> rename---> Update---> an error occur: Access to the path is denied D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder
Help!
the path "D:\\C#Projects\\website\\Lecturer\\giangvien\\New folder" probably doesn't exist. I'm thinking you meant "D:\C#Projects\website\Lecturer\giangvien\New folder". I think what #CharmingInferno was trying to get at was that when you use # in front of a string you don't need to use escape characters as it takes the text as is like the following
string g = "\\\\server\\share\\file.txt"; // \\server\share\file.txt
string h = #"\\server\share\file.txt"; // \\server\share\file.txt
However you are putting your values in the EditValue string array should be corrected.
I had the same problem just now.
Using
Directory.Move(srcDirectory, dstDirectory);
sometimes caused the Access to the path /dstDirectory/ is denied exception, sometimes it don't.
The following solved for me.
new DirectoryInfo(srcDirectory).MoveTo(dstDirectory);

File.Exists isn't find the document but it is there

So something must be wrong with my string.
I am grabbing the value from a SQL database which comes out like this:
while (reader.Read())
{
// Row Values
// 0 = UID
// 1 = CreatedDate
// 2 = Location
documentID = reader.GetGuid(0);
fileName = reader.GetSqlValue(0).ToString() + ".zip";
location = reader.GetString(2);
createdDate = reader.GetDateTime(1);
The values returned from the database are as follows:
GUID: DC5A30D7-D528-4BA4-AA5A-5ECEB2CD9006
fileName: DC5A30D7-D528-4BA4-AA5A-5ECEB2CD9006.zip
Location: \\192.168.22.1\documentation
if (!DoesFileExist(location + fileName))
{
// Log error to database
}
static bool DoesFileExist(string location)
{
bool doesExist = false;
if (File.Exists(location))
{
doesExist = true;
}
return doesExist;
}
When it gets to the part File.Exists(location) it passes over it as if it dind't exist. Bur it does... When I navigate to it in an Explorer I find the zip file just fine...
What am I doing wrong here?
UID CreatedDate Location
DC5A30D7-D528-4BA4-AA5A-5ECEB2CD9006 2009-10-28 11:17:06.690 \\192.168.22.1\documentation
As it is written in the example above, the Location + Filename doesn't produce a correct full filename. There is no backslash to separate the path from the filename.
I suggest to use the appropriate method Path.Combine from the class (System.IO.Path) to make the correct full filename
if (!DoesFileExist(Path.Combine(location, fileName)))
The way I see it, you're sending: "\192.168.22.1\documentationDC5A30D7-D528-4BA4-AA5A-5ECEB2CD9006.zip" to the method.
Try putting another "\" there.
Most of the time I have a problem like that, it is because of permissions. Often, the user for the file explorer is different that is trying to find the file with file exists. If everything is correct with the location, the next place to look would be the permissions.

Categories

Resources