How to rename a file while uploading - c#

I am uploading file.so I want to change my file name.
string createfolder = "E:/tmp/jobres/" + uId;
System.IO.Directory.CreateDirectory(createfolder);
string newfilename = txtname.Text + "Resume" + fileExtension;
AsyncFileUpload1.SaveAs(Path.Combine(createfolder,newfilename ));
This time file is in different format then its not replacing.

string createfolder = "E:/tmp/jobres/" + uId;
System.IO.Directory.CreateDirectory(createfolder);
//AsyncFileUpload1.SaveAs(Path.Combine(createfolder,"Give Something Here whatever is changing at all time like time value"+AsyncFileUpload1.PostedFile.FileName));
AsyncFileUpload1.SaveAs(Path.Combine(createfolder,"DateTime.Now"+AsyncFileUpload1.PostedFile.FileName));

Related

c# file copy to a server

I want to copy a pdf to my own server but i get an error about path.
the codes like that:
string filepath = System.IO.Path.GetFullPath(open.FileName);
when i pick the pdf I want to save it to my server with this codes:
string filename = "New name" + ".pdf";
string newpath = #"\\WDMyCloud\Certificates\" + filename;
File.Copy(filepath, newpath, true);
But when i run this code i take an error like "invalid path name.

How to change the file name before store in file and database

this code is to check does the user has upload any file and the file namd.
if (FileUpload1.HasFile) {
fileName = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Data/") + fileName);
fileLocation = Server.MapPath("~/Data/") + fileName;
}
I wonder can I add the current date on the end of the file name. my file can be any type of file. I do try add on FileName= FileUpload1.FileName+updateon; but the file will save as example.jpg11062015 and the file will be corrupted.
anyone has any idea how to do it?
You can use Path to separate FileName into a file name and an extension, insert the date in the middle, and combine them back, like this:
var fn = Path.GetFileNameWithoutExtension(FileUpload1.FileName);
var ext = Path.GetExtension(FileUpload1.FileName);
var fileName = string.Format("{0}{1:yyyy-MM-dd}.{2}", fn, DateTime.Now, ext);
Try parsing the file name into parts, and inserting your date in between, like this:
var newFileName = Path.GetFileNameWithoutExtension(FileUpload1.FileName)
+ "11062015" // or wherever the date is coming from
+ Path.GetExtension(FileUpload1.FileName);
Original file name: "someFile.ext"
Modified file name: "someFile11062015.ext"

replace file with new one with timestamp

I have a file in a directory:
Path.Combine(dir1, "participants.txt")
I want to check if participants.txt exists in dir1. And if it does copy it to a new file named participants[timestamp].txt. And replace the old one with the information lines.
I have tried this:
if (File.Exists(Path.Combine(dir1, "participants.txt")))
{
File.Copy("participants.txt", "participants" + Stopwatch.GetTimestamp().ToString() + ".txt");
File.WriteAllLines("participants.txt", lines);
}
But this isn't working. Any ideas?
You are missing the full path in your filename specifiers:
String source = Path.Combine(dir1, "participants.txt");
if (File.Exists(source)) {
File.Copy(source, Path.Combine(dir1, "participants" + Stopwatch.GetTimestamp().ToString() + ".txt"));
File.WriteAllLines(source, lines);
}

When to delete generated file using asp.net

I have a template excel file to generate excel files from it.
My code is as follows (This part is to create a new excel file from the template):
string currentFN = PropertyFinalResult[0].Fecha;
string fixCurrentFN = currentFN.Replace('/', '_');
string currentTime = DateTime.Now.ToLongTimeString();
string fixCurrentTime = currentTime.Replace(':', '_');
string addToFileName = fixCurrentTime.Replace(' ', '_');
string newFN = fixCurrentFN + "-" + addToFileName;
string SourceFile = Request.PhysicalApplicationPath + "Template\\ExcelTemplate.xlsx";
string DestFile = Request.PhysicalApplicationPath + "Template\\" + newFN + ".xlsx";
//To keep FileName for posterior deletion
Session["sDestFile"] = DestFile;
try
{
File.Copy(SourceFile, DestFile);
}
catch (Exception ex)
{
lblErrorSavingToDB.Text = "Error: " + ex.Message;
lblErrorSavingToDB.Visible = true;
}
after that I open the new excel file, insert the records in it and then, stream the file to the user by doing this:
//Streaming file to client
string fileName = newFN + ".xlsx";
Response.Redirect("../Template/" + fileName);
Now, my question is, whether the user save or not the file, when should I delete the generated file? I would prefer once the user closes the popup window regarding Open or Save the file. But how to know when the user closes that window?
You can use TransmitFile and then close once the transmission is over. Example:
try
{
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename=\"" + Path.GetFileName(path.FullName) + "\"");
Response.AddHeader("content-length", path.Length.ToString());
Response.TransmitFile(path.FullName);
Response.Flush();
}
finally
{
File.Delete(Server.MapPath("~/"+tpacode+".zip"));
}
When to delete the files (or maybe it's better to say "how long to keep the files") is a question that is best answered by your application's business rules.
In the past, in low-traffic applications, I've used a "clean-up" routine to delete files older than a certain threshold. That clean-up gets performed when a new file is created, and at that time any file in the designated folder that was older than the threshold would be deleted.

Asp.net finding and downloading file

I have File Upload form which users use to upload certain files on the server. The files are uploaded in path that look like this.
"G:\\VS\\Ticketing System2\\UploadedFiles\\" + ProjectId + "\\" + ticketId + "\\TicketFiles\\";
After that I have a repeater which displays some data and have a hyperlink. I want to name the hyperlink"Download files(" + fileCount + ")" and onclicked it should display a regular Save As window. Can you give me some code to do that. I've never done something like this.
To get the number of files in the directory, you need to use IO. Then
string path = #"G:\\VS\\Ticketing System2\\UploadedFiles\\" + ProjectId + "\\" + ticketId + "\\TicketFiles\\";
int numFiles = Directory.GetFiles(path).Length;
Then in your page_load, just change to .Text of the link to include the numFiles variable

Categories

Resources