File upload path not saving right - c#

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

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.

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

Access to the path 'T:\T Drive.vhd' is denied

I'm writing a backup program for our new server. I'm an administrator, and I'm learning a lot. The issue is that I can back up a file on the c:\ drive to the c:\ drive, but not for the drives on the SAN, like when I try to backup a file on the T drive (SAN) to the H drive (server). I tried using SetAttributes like
Why is access to the path denied?
but it basically gives the same error message to try setAttributes as I did when I tried to copy the file. This is a portion of my log:
12/30/2013 2:14:57 PM Successful backup of file C:\test\iceCreamCake_12_30_2013_1414P.docx
12/30/2013 2:14:57 PM exception during backupSystem.UnauthorizedAccessException: Access to the path 'T:\T Drive.vhd' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.SetAttributes(String path, FileAttributes fileAttributes)
at Bak.BackItUp(String fromDrive, String toDrive) in C:\Users\michele\BackupProj\ServerBackup\ServerBackup\Backup.cs:line 36
12/30/2013 2:14:57 PM exception during backupSystem.UnauthorizedAccessException: Access to the path 'S:\SQL Database.vhd' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.SetAttributes(String path, FileAttributes fileAttributes)
at Bak.BackItUp(String fromDrive, String toDrive) in C:\Users\michele\BackupProj\ServerBackup\ServerBackup\Backup.cs:line 36
Shouldn't I be able to run my program to do the backup if I'm logged on as Administrator?
Here's part of the code:
try
{
if (System.IO.File.Exists(fromDrive))
{
result = 4;
if (System.IO.Directory.Exists(toDrive))
{
string oldFileName = Path.GetFileName(fromDrive); //file name only
string sourcePath = Path.GetDirectoryName(fromDrive); //path only
string newFileName = AppendFileNameWithDate(oldFileName); //file name with date added
string destFile = System.IO.Path.Combine(toDrive, newFileName); //full path of final destination with new file name
result = 3;
System.IO.File.SetAttributes(fromDrive, FileAttributes.Normal);
System.IO.File.Copy(fromDrive, destFile, true); //copy backupFileName to toDrive, overwrite destination file if it already exists
if (File.Exists(destFile))
{
Logging.Logging.Instance.Debug("Successful backup of file " + destFile);
result = 2;
}
else
{
result = -2;
Logging.Logging.Instance.Debug("Backup *failure of file " + destFile);
}
}
else
{
Logging.Logging.Instance.Debug("to Drive does not exist: " + toDrive);
result = -1;
}
}
else
{
Logging.Logging.Instance.Debug("from Drive does not exist: " + fromDrive);
result = -1;
}
}
catch (Exception ex)
{
Logging.Logging.Instance.Debug("exception during backup" + ex.ToString());
}
The directory strings are like this:
string cDrive = #"C:\backup\2013\iceCreamCake.docx";
string tDrive = #"T:\T Drive.vhd";
string sDrive = #"S:\SQL Database.vhd";
string cDriveToLocation = #"C:\test";
string tDriveToLocation = #"H:\";
string sDriveToLocation = #"E:\";
string vDriveToLocation = #"G:\";
Thanks,
Michele
Thanks for all your help. I wound up specifically adding (security access to) each of my logins (usxxxxxx and M_CL) to the properties of the files/directories, then editing the privileges to get full control, and also removing all spaces in the file name for the t:\ drive file and the c:\ directories file (it was failing for my M_Cl login but not usxxxx), and it worked for c:\ and t:. We thought the general Users and Administrators file access priviledges would work, but it didn't. The other thing I added was instead of having the complete string for t drive defined with file, I did a path combine like
string sDrive = Path.Combine(#"S:\", #"SQL_Database.vhd");

I'm trying to compress some files from one directory to another but I'm getting access denied on one of the directories why?

In the constructor of Form1 I did:
contentDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\SF_" + currentDate;
zippedFileDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\Default_ZippedFile_Directory";
if (!Directory.Exists(zippedFileDirectory))
{
Directory.CreateDirectory(zippedFileDirectory);
}
if (!Directory.Exists(contentDirectory))
{
Directory.CreateDirectory(contentDirectory);
}
Checked with breakpoint first time zippedFileDirectory not exist create it and if exist nothing. Same for the contentDirectory.
Now I have the contentDirectory here:
C:\\Users\\bout0_000\\AppData\\Local\\Diagnostic_Tool_Blue_Screen\\Diagnostic Tool Blue Screen\\SF_04-08-13
Inside the contentDirectory I have something like 10 files.
Then zippedFileDirectory is:
C:\\Users\\bout0_000\\AppData\\Local\\Diagnostic_Tool_Blue_Screen\\Diagnostic Tool Blue Screen\\Default_ZippedFile_Directory
This directory is empty.
Then I have this Compress() method:
private void Compress()
{
string source = contentDirectory;
string output = zippedFileDirectory;
string programFilesX86 = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86) + "\\Diagnostic Tool\\7z.dll";
if (File.Exists(programFilesX86))
{
SevenZipExtractor.SetLibraryPath(programFilesX86);
}
string programFiles = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\Diagnostic Tool\\7z.dll";
if (File.Exists(programFiles))
{
SevenZipExtractor.SetLibraryPath(programFiles);
}
SevenZipCompressor compressor = new SevenZipCompressor();
compressor.ArchiveFormat = OutArchiveFormat.Zip;
compressor.CompressionMode = CompressionMode.Create;
compressor.TempFolderPath = System.IO.Path.GetTempPath();
compressor.CompressDirectory(source, output);
Process.Start(Path.GetFullPath(zippedFileDirectory));
}
For some reason on the line:
compressor.CompressDirectory(source, output);
I'm getting the exception:
Access to the path 'C:\Users\bout0_000\AppData\Local\Diagnostic_Tool_Blue_Screen\Diagnostic Tool Blue Screen\Default_ZippedFile_Directory' is denied.
System.UnauthorizedAccessException was unhandled
HResult=-2147024891
Message=Access to the path 'C:\Users\bout0_000\AppData\Local\Diagnostic_Tool_Blue_Screen\Diagnostic Tool Blue Screen\Default_ZippedFile_Directory' is denied.
I don't get it why this zippedFileDirectory is locked or access denied ?
If I select any other directory as source for example d:\test there is no problem.
It doesn't work because you pass a directory name for the second parameter to CompressDirectory.
You should pass a file name like....
string output = Path.Combine(zippedFileDirectory, "MyZipFile.7z");
.....
compressor.CompressDirectory(source, output);

Get list of files for asp.net web app returning not a valid virtual path

I am trying to get a list of files in a folder on the filesystem in my .net web app. When I run the app, I am getting an error that says that the directory "is not a valid virtual path". How do I get this to return files, that are in my WebApp's directory (they are located in {webapp root}\docs\custFiles).
try
{
List<string> custFiles = new List<string>();
StringBuilder dir = new StringBuilder(#"~\docs\custFiles\");
dir.Append(custNo + #"\");
string directory = HttpContext.Current.Server.MapPath(dir.ToString());
bool IsExists = System.IO.Directory.Exists(directory);
if (!IsExists)
{
string[] fileList = Directory.GetFiles(directory);
custFiles = (fileList.ToList());
}
return custFiles;
}
catch (Exception ex)
{
throw ex;
}
The problem is this line:
bool IsExists = System.IO.Directory.Exists(Server.MapPath(directory));
As you've already built the directory name here:
string directory = HttpContext.Current.Server.MapPath(dir.ToString());
You can just use the Exists call without Server.MapPath:
bool IsExists = System.IO.Directory.Exists(directory);
Well, It seems problem with virtual path you are passing. Instead that try this.
String directory=Server.MapPath("~/docs/custFiles");
if(System.IO.Directory.Exists(directory))
{
//do your coding..
}

Categories

Resources