How to retrieve "Last Modified Date" of uploaded file in ASP.Net - c#

I am developing a website, in which client uploads some document files like doc, docx, htm, html, txt, pdf etc. I want to retrieve last modified date of an uploaded file. I have created one handler(.ashx) which does the job of saving the files.
Following is the code:
HttpPostedFile file = context.Request.Files[i];
string fileName = file.FileName;
file.SaveAs(Path.Combine(uploadPath, filename));
As you can see, its very simple to save the file using file.SaveAs() method. But this HttpPostedFile class is not exposing any property to retrieve last modified date of file.
So can anyone tell me how to retrieve last modified date of file before saving it to hard disk?

Today you can access to this information from client side using HTML5 api
//fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput">
var fileInput = document.getElementById("myfileinput");
// files is a FileList object (simliar to NodeList)
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
alert(files[i].name + " has a last modified date of " + files[i].lastModifiedDate);
}
Source and more information

You can't do this. An HTTP post request does not contain this information about an uploaded file.

Rau,
You can only get the date once it's on the server. If you're ok with this, then try:
string strLastModified =
System.IO.File.GetLastWriteTime(Server.MapPath("myFile.txt")).ToString("D");
the further caveat here being that this datetime will be the date at which it was saved on the server and not the datetime of the original file.

It is not possible, until you save the file to disk.

You typically cannot get the last modified date because the date is not stored in the file.
The Operating System actually stores file attributes like Created, Accessed, and Last Modified. See Where are “last modified date” and “last accessed date” saved?
(I say typically because certain file types like images may have EXIF tag data like the date/time the photo was taken.)

Related

How to Handle Multiple Image Uploads in ASP.NET MVC Website?

I am using dropzone.js to upload multiple images to a .NET MVC website. When the images come into the server, I resize them, save information to the database, and then save the actual image on the server in a folder. When I upload them one at a time this works, but if I do multiple uploads at once, I get this error every few uploads:
A generic error occurred in GDI+
Googling this seems that this is a generic error when you are unable to save a file as some other process is using the location. I assume that the multiple uploads are trying to save in the same folder at the same time and one dies. They are not the same filename.
How can I avoid this? Is there a way to have the threads wait for one to finish before it tries saving in the same folder? I'm wondering if there is a method that is like the await call where it waits until it can save.
Edit More Code
I can't copy my whole function as it's very long etc but the part that saves is the following:
//Now we will try saving the actual file. Generate the file name.
String savedFileName = PhotoTools.GenerateImageFileName(photo.image_base_file_name);
String thumbnailSavedFileName = PhotoTools.GenerateImageFileName(photo.image_base_file_name, true);
//Store the file path (directory) that we are going to save the image to.
String directoryToSave = Server.MapPath(Constants.ImageDirectory + $"/{house_id}");
//Create the directory. This function will not do anything if it already exists.
Directory.CreateDirectory(directoryToSave);
//Save the images to the filesystem.
mainImage.Save(Path.Combine(directoryToSave, savedFileName), ImageFormat.Jpeg);
thumbnailImage.Save(Path.Combine(directoryToSave, thumbnailSavedFileName), ImageFormat.Jpeg);
They should not be the same filename as the file name is created as such:
/// <summary>
/// Generates the base property image filename based on the passed in information.
/// </summary>
/// <param name="propName">The house name that we will use for the file name.</param>
/// <returns>The generated file name.</returns>
public static String GenerateBaseImageFileName(String propName)
{
//Save the current datetime to create the filename with.
DateTime now = DateTime.Now;
//Generate the name.
return $"{CommonTools.RemoveSpecialCharacters(propName).Replace(" ","-")}-{now.Hour}{now.Second}{now.Millisecond}";
}
Usually this error A generic error occurred in GDI+ mean that the file or the path doesn't exist:
so try for example to check if the directory exist or create it if not .. and then double check if you have already a file with same name or if the full path exist:
try:
var guid = Guid.New().ToString(); //<-- generate new random guid
//Store the file path (directory) that we are going to save the image to.
String directoryToSave = Server.MapPath(Constants.ImageDirectory + $"/{house_id}");
//Create the directory. This function will not do anything if it already exists.
if(!Directory.Exist(directoryToSave)
Directory.CreateDirectory(directoryToSave);
//Save the images to the filesystem.
mainImage.Save(Path.Combine(directoryToSave, savedFileName + "_" + guid), ImageFormat.Jpeg);
Hope it helps you

Creating a file path to a file, where the files name changes daily

I am trying to get a file path to a file where the file name keep changing. So far, I have a file path to a particular log file named 18052015.log. I am specifying the file name and extension, 18052015.log.
string strFilePath = #"\\server-1\public\logs\18052015.log";
The file name matches a date. Each day a new file is generated. So, tomorrow there will be a file named 19052015.log
The only file I'm interested in retrieving is the one named date.log as in 18052015.log or 19052015.log. I cannot use the option to just retrieve any log with a .log extension, as there are many other files in the same logs folder, all with the file extension .log e.g AFile.log, BFile.log, 1File.log, 2File.log. So, the following code doesn't help.
string[] files = Directory.GetFiles(strFilePath, "*.log", SearchOption.AllDirectories);
My question is, how, if the name of the file changes daily, can I retrieve that one log without specifying it's name?
I think you're looking for DateTime.Now in a specified format:
string directoryPath = #"\\server-1\public\logs;"
string fullLogPath = string.Format(#"{0}\{1:ddMMyyyy}.log", directoryPath, DateTime.Now);
To combine all solutions:
string fullFilename = Path.Combine( #"\\server-1\public\logs", string.Format("{0:ddMMyyyy}.log", myTime) );
And to correctly use Path.Combine instead of string'formatting around :-)
Use DateTime
Here is a little example:
DateTime myTime = DateTime.Now;
string fileName = string.Format("{0}{1}{2}.log", myTime.Date, myTime.Month, myTime.Year);
DateTime.Now gives you the Time from your computer. then you can extract the Date, Month and Year from the Struct.

Open file by part of his name

I need to open file from folder by part of name.
I have files in one folder for example all files are in c:\temp\
Names of files are in format id_yyyyMMdd.pdf, where id is some number, id of file , and id is always unique, yyyyMMdd are date in format year,month,day.
Now in program i get id and i need to find file with that id, then check date when file is created , and if there are new version of file(blob in database) i need to write this new file to disk and than open it, if this is last version of file i need just open.(i have PDFs like blob, and i need to check is on hard disk last version file.) I know how to write pdf from blob to file i cannot find way to open(or find) file with part of name , and thaen get second part(date) to compare it.
Any suggestions?
Sample:
on hard disk i have files:
c:\temp\12345_20140508.pdf
c:\temp\12346_20140508.pdf
In database table i have
id(12345) date(08-MAY-2014) and pdf1 file like blob.
id(12346) date(10-MAY-2014) and pdf2 file like blob.
Now in program I select id "12345" because dates are same i need to open file 12345_20140508.pdf
When i get select id 12346 i need first get file file from database because date in database is newer than date on hard disk, remove file 12346_20140508.pdf and save new file like 12346_20140510.pdf and than open.
If it is need i can change format of name.
I supposed the main problem you met is "how to find the newest file by id". So may be you can try this code. It can find the last created file start with some id. Once you get the file, I thought other things won't be a problem to you.
var directoryInfo = new DirectoryInfo(#"c:\temp");
var latestFile = directoryInfo.GetFiles()
.Where(f => f.Name.StartsWith("12345_"))
.OrderByDescending(f => f.CreationTime)
.FirstOrDefault();
what you should do is:
string searchPattern = "what you want to open";
File.Open(Directory.GetFiles(#"c:\", searchPattern + "*").First());
That will open the file in the c# sense,
however to open in an app use
Process.Start("notepad.exe", Directory.GetFiles(#"c:\", searchPattern + "*").First());
if you want to open them all wrap this in a foreach
foreach (var file in Directory.GetFiles(#"c:\", searchPattern + "*"))
{
//do stuff
}

FiIeInfo.CreationTime. How to read correct value?

I have file upload control on .aspx page, I want to upload an image at a time whose location is not always the same, could be in same directory as .sln, on desktop, anywhere.
I am using this code to read the file creation time
string savePath = MapPath("~/" + Path.GetFileName(e.FileName));
FileInfo MyFileInfo = new FileInfo(savePath);
string dt = MyFileInfo.CreationTime.Day.ToString();
string mn = MyFileInfo.CreationTime.Month.ToString();
string yr = MyFileInfo.CreationTime.Year.ToString();
I have noticed one thing that
If the image is in the same folder as the website, it gives me correct values for all
dt , mn and yr
But if it's outside that location, it always gives me same value everytime
{01/01/1601 00:00:00}
Not sure how to sort this out?
any advice, helpful code? thanks
It seems you do not understand the client/server barrier yet. Paths from the client are not meaningful on the server.
It so happens that your website is running on the same machine as the client because you are debugging locally. That is just a coincidence and it allows your code to sometimes work (by coincidence).
Proper file uploading works by ignoring the path and reading from the stream provided by the file upload control. A file upload is just a stream of bytes to the server.

Creating files programmatically and getting the file names from WP7 isolated storage

I am building an app which requires saving a form whenever user enter the details. I want each form to be stored in separate .dat file. Using GUID as file names, I am able to store the data in separate files now. But I am not able to retrieve all the filenames and bind it to a listbox of hyperlinkbutton, on click of which will show all the data stored in the particular file. Please help!
Maybe you want to have a look at:
http://msdn.microsoft.com/en-us/library/cc190395(v=vs.95).aspx
"GetFileNames" is a method of "IsolatedStorageFile" which shows all the files in the directory it is pointing to.
In this question you can get an example:
How to read names of files stored in IsolatedStorage
Try using the GetFilesNames method of your IsolatedStorageFile. Use a wildcard (*.dat) to retrieve a list of your files.
For example:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
string pattern = "*.dat";
string[] files = store.GetFileNames(pattern);
}

Categories