Upload multiple files & create zip - c#

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

Related

Handle UnauthorizedAccessException When Directory.CreateDirectory() Run

I have a method that is helps to Create a Directory ifNotExist and Save the path of the File ,...
Now I have a little problem, There is an Exception casted when Directory.CreateDirectory(savePath); Runs. and I can't still get it right. I would like to know what I am doing wrong and how to fix it. Anyone Subjections is welcome. Thanks
Here is My Method:
protected void ASPxUpload_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
String savepath = String.Format("{0}{1}\\", MapPath(#"~\TicketUploads\"), Session["lastcallid"]);
if (!Directory.Exists(savepath))
{
Directory.CreateDirectory(savepath);
}
String savefile = String.Format("{0}{1}", savepath, e.UploadedFile.FileName);
e.UploadedFile.SaveAs(savefile);
String urlPath = String.Format("{0}{1}\\{2}", #"~\TicketUploads\", Session["lastcallid"], e.UploadedFile.FileName);
fault_detail fltdet = session.GetObjectByKey<fault_detail>(Convert.ToInt32(Session["lastcallid"]));
fltdet.hasattachment = "Y";
fltdet.AttachUrl = urlPath;
fltdet.Save();
}
}
For more details of What I trying to do:
It simple allows the web server to identify the ID of the log user. and With that ID, We should therefore create a folder in Ticketuploads Folder. Which is like we are trying to create 2 folders at the same time. That is why I use: "{0}{1}\\"
please try this
string sessionVariable = Convert.ToString(Session["lastcallid"]);
string path = Path.Combine(MapPath(#"~\TicketUploads\"), sessionVariable);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Also
I have Add Administration Permission to the Folder. As a Local user with IIS System. user Add Example: IIS_IUSRS(Username\IIS_IUSRS) That's it.

How do I get the folder for the currently open file in c#

I am writing a wizard that pulls information from a database like file. This wizard doesn't get compiled, it just runs on command. I am not sure the correct term for that.
The issue is, I need to enter more information which will manipulate the database, and I want to store the values into a csv file that I use to manipulate the database.
So the question is: How do I get the folder for the currently open file in a c# application so that I can save a csv file to that folder?
edit: The path needs to be dynamic. Each database file is stored in a separate folder. I need the wizard to save to which ever folder I just opened the file from.
edit2 :
I am not opening the file programmatically. The file is being open by the user in the application. So, the user opens a file, and a bunch of database information is displayed. He then runs a wizard on that data where he can enter some coefficients, etc .. and that will change the information in the database file. I need to be able to store the coefficients he enters into the folder that contains the database file that he opened. I cannot access / change the application code, only the wizard code.
Thanks
Something like this?
var file = "C:\\Users\\Me\\Desktop\\Test.txt";
var fileLocation = file.Substring(0, file.LastIndexOf("\\"));
You can use this:
string path = Path.GetFullPath(Directory.GetCurrentDirectory()).TrimEnd(Path.DirectorySeparatorChar);
string directoryName = Path.GetFileName(path);
I found this solution in this thread
Get the (last part of) current directory name in C#
Try
//Or where ever the database returns the file is stored
var filename = "C:\\Temp\\File\\Test.txt";
var path = System.IO.Path.GetDirectoryName(filename);
Should return C:\Temp\File
Source : https://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
Try using DirectoryInfo to get information about any directory:
using System;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
if (di != null)
{
FileInfo[] subFiles = di.GetFiles();
if (subFiles.Length > 0)
{
Console.WriteLine("Files:");
foreach (FileInfo subFile in subFiles)
{
Console.WriteLine(" " + subFile.Name + " (" + subFile.Length + " bytes) " + "Directory name: "
+ di.Name + " Directory full name: " + di.FullName);
}
}
Console.ReadKey();
}
}
}
}

403 on file creation while using Hadoop.WebHDFSClient, Although was able to create Folders in HDFS

This code works till the folder creation then could not create file and throws 403. am I missing some thing here for authentication. I am new to Hadoop and trying to learn hdInsight.
private static void uploadFile()
{
//set variables
string srcFileName = #"./prime/in/integers.txt";
string destFolderName = #"/prime/in";
string destFileName = #"integers.txt";
string outputFolderName= #"/prime/out";
//connect to hadoop cluster
Uri myUri = new Uri("http://DXPZN72-LP:50070");
string userName = "hadoop";
WebHDFSClient myClient = new WebHDFSClient(myUri, userName);
//drop destination directory (if exists)
myClient.DeleteDirectory(destFolderName, true).Wait();
//create destination directory
myClient.CreateDirectory(destFolderName).Wait();
//create outputFolderName directory
myClient.CreateDirectory(outputFolderName).Wait();
//load file to destination directory
var res= myClient.CreateFile(srcFileName, "/" +destFileName);
res.Wait();
//list file contents of destination directory
Console.WriteLine();
Console.WriteLine("Contents of " +destFolderName);
myClient.GetDirectoryStatus(destFolderName).ContinueWith(
ds => ds.Result.Files.ToList().ForEach(
f => Console.WriteLine("t" +f.PathSuffix)
));
//keep command window open until user presses enter
Console.ReadLine();
}
This was found to be a service needed restarted.Although I was able to create folders but was not able to create File with a 403.
I restarted my machine then tried again, the issue was gone and I was able to create file as well.

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

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

Categories

Resources