How to copy file in asp.net - c#

I use ASP.net and have a .docx file in website:
Server.MapPath("~") + #"Files\tmp.docx".
I want copy this file to
Server.MapPath("~") + #"Files\Docx\" with "D210" named.
How to copy this file and rename it?

you need to do IO job so do not forget to add Using System.IO;
and this is the code you need:
//1.Prepare the name for renaming
string newName = "D210";
//2.Create the Folder if it doesn't already exist
if(!Directory.Exists(Server.MapPath("~")+#"\Files\Docx\"))
Directory.CreateDirectory(Server.MapPath("~")+#"\Files\Docx\");
//3.Copy the file with the new name
File.Copy(Server.MapPath("~") + #"Files\tmp.docx",Server.MapPath("~")+#"\Files\Docx\"+newName+".docx");

Related

Trying to upload a PDF file using ASP.NET MVC is causing an error "Object reference not set to an instance of an object"

I am trying to upload a PDF file to a folder and save the file path to the database in ASP.NET MVC. I can use this same method to save a JPG file while it is throwing an error for a PDF file.
Am I missing out anything?
This is my code:
DirectoryInfo dir = new DirectoryInfo(HttpContext.Server.MapPath("~/LoanDocuments/Uploads/"));
if (!dir.Exists)
{
dir.Create();
}
// Uploading PDF and saving to database
// Extract PDF File Name.
string fileName = initiateLoanRequest.Firstname + initiateLoanRequest.Surname + Loan_RequestID; //The filename will be FirstnameSurnameLoan_RequestID
// Set the PDF File Path.
string filePath = "/LoanDocuments/Uploads/" + fileName + ".pdf";
// Save the uploaded document in Folder.
loan_Document.SaveAs(Server.MapPath(filePath));
What am I missing out in this? It works well when I used same code in another module for JPG files.
Please note that the loan_Document is posted as HttpPostedFileBase loan_Document.
Issue resolved. The Posted file name I am sending from the View is different from the postedfile name I am using at the Controller. So using the same names resolved the issue.
Thank you

How to Get current date and create directory Everyday in C#?

get current date and make directory and second when directory is created, in that directory I have to store excel file and also save file as current date.
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists("C:\\Users\\Krupal\\Desktop\\" + Todaysdate))
{
Directory.CreateDirectory("C:\\Users\\Krupal\\Desktop\\" + Todaysdate);
}
This code have made directory with current date.
But when I want to store file in that directory, it generates the error:
Could not find a part of the path
'D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
Belove path is store excel file that i have to store.
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Actually you are making the directory in a path then you are saving the .xls in another path.
You are making the directory using this path:
"C:\\Users\\Krupal\\Desktop\\" + Todaysdate
Then, here the path where you are trying to save the .xls:
Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"
The error shows the problem clearly, it could not fin this path:
D:\WORK\RNSB\RNSB\bin\Debug\22-01-2020\22-01-2020.XLS
While creating the .xls you are omitting the root path, so the process looks for the path 22-01-2020\22-01-2020.XLS in his working directory D:\WORK\RNSB\RNSB\bin\Debug.
You just need to align those paths: I sugget you to use relative paths, so here how you should fix your code:
String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy");
if (!Directory.Exists(Todaysdate))
{
Directory.CreateDirectory(Todaysdate);
}
//then
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
I presume you are running your WinForms application in Debug mode. This means that your current path is [your application path]\bin\Debug. If you look in file explorer, you will find that an executable has been created there. When using StreamWriter without an absolute file name, the file it tries to create is relative to the current execution path (in your case 'D:\WORK\RNSB\RNSB\bin\Debug'). StreamWriter will create a new file, if one does not exist, but it will not create a new folder, and you are passing it Todaysdate + "\\" which is effectively a new folder. Hence you are getting the error message.
To fix your problem, you need to provide the absolute path to your newly created directory thus:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:\\Users\\Krupal\\Desktop\\" + Todaysdate+"\\"+DateTime.Now.ToString("dd/MM/yyyy") +".XLS"))
Winforms always expect directories inside Debug Folder, since it's EXE file is inside Debug and try to find it inside Debug folder.
In error it clearly shows that it is looking inside "Debug" folder.
Can you check whether File Exists in the mentioned folder created by you in C Drive.
// To Write File
System.IO.File.WriteAllLines(#"C:\Users\Public\TestFolder\WriteLines.txt", lines);
You can follow this MSDN Post, hope it helps, if Yes, please Upvote it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file

ZipArchiveMode keep folder integrity

I am trying to use the ZipArchiveMode to zip up a few files. The files are in different directories.
zipFile.CreateEntryFromFile(file, Path.GetFileName(file), compression);
I'm calling this for each file.
Is there a way to keep the folder integrity within the file so that it unzips in to the correct folder?
If not, do I have any other options for compressing files?
Thank you
Instead of just Path.GetFileName(file), use whatever portion of the fullname of the file is appropriate for your application. Something like this might work:
FileInfo fi = new FileInfo(file);
string path = fi.Directory.Parent + "\\" + fi.Name;

Cannot create a file when it already exists using File.Move

I was trying to move a file from my Resx to my PC, but I'm keep having problems.
So I import a folder named "bad" in the Resources and I use the File.Move method to move the folder "bad" into my PC.
But the program keeps crashing because it says: Cannot create a file when its already exists.
Here the code I use:
//txtpath is the root folder. I let the user choose the root folder and save it in txtpath.text
private void btnbadname_Click(object sender, EventArgs e)
{
string source = "Resources\bad";
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App";
File.Move(source, destination);
MessageBox.Show("脏话ID已开启, 教程请点击下面的链接");
}
The destination Directory cannot exist. In your code you are creating the Directory if it doesn't exist and then trying to move your directory, the Move Method will create the directory for you. If the Directory already exists you will need to Delete it or Move it.
See:
Cannot create a file when that file already exists when using Directory.Move
Destination supposed to have the filename as well
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App\yourfilename.ext";
You are using File.Move to move directory, why not using Directory.Move.
The MSDN documentation will only move files from a source to a destination, while Directory.Move will move the directory itself.
If I misunderstood you, and you want to move a file;
You can check if the file exists before or not using something like:
if(File.Exists(fileName))
File.Delete(fileName);
Edit:
If you want to iterate through the directory and make sure that the file doesn't exist before moving it, you can use something like:
//Set the location of your directories
string sourceDirectory = #"";
string destDirectory = #"";
//Check if the directory exists, and if not create it
if (!Directory.Exists(destDirectory))
Directory.CreateDirectory(destDirectory);
DirectoryInfo sourceDirInfo = new DirectoryInfo(sourceDirectory);
//Iterate through directory and check the existance of each file
foreach (FileInfo sourceFileInfo in sourceDirInfo.GetFiles())
{
string fileName = sourceFileInfo.Name;
string destFile = Path.Combine(destDirectory, fileName);
if (File.Exists(destFile))
File.Delete(destFile);
//Finally move the file
File.Move(sourceFileInfo.FullName, destFile);
}
When using MoveTo, provide the full path of where you are sending the file, including the file name, eg, pic123.jpg. If you use DirectoryInfo to get an array of files and want to move any of them, append the Name property of the file to the directory path where you are sending the file.
imgFile.MoveTo("C:\myPictures\ArchiveFolder\pic123.jpg")

Meaningful Auto Rename of File using ASP.NET

Coding Platform: ASP.NET 4.0 C#
Consider the following scenario.
I am uploading a file named "StackOverflow.doc" to the folder Documents using asp:FileUpload.
But the folder documents already have a file named "StackOverflow.doc".
In this situation I would like to rename my file as StackOverflow(1).doc.
I do know how to make file names unique using GUID or by assigning temporary names.
But what I need is a windows explorer like solution. Which is the best way to approach it?
P.S: The solution should be redundant. That is, if there are files named StackOverflow.doc and StackOverflow(1).doc, my renamed file should be StackOverflow(2).doc
Here is one approach to getting a file name as you are asking (the file path logic not included for brevity):
string fileName = downloadFileName;
string fileExt = downloadFileExtention;
string fullFileName = string.Format("{0}.{1}", fileName, fileExt);
int counter = 0;
while(File.Exists(fullFileName))
{
counter++;
fullFileName = string.Format("{0}({1}).{2}", fileName, counter, fileExt);
}
// Write the file to fullFileName

Categories

Resources