Get name and create date of files in a directory

Long time developer / total newbie @ C#.

I want to retrieve a list of files AND the file create date and load them 
into an array for further processing…

I found the following which works well 
Directory.GetFiles(sourceDir, "*.*"

But I can’t find anything similar to file and file create dates.  Do I need 
to retrieve the create dates one at a time (using foreach or for) based on 
the results of GetFiles?

0
Utf
1/4/2010 9:12:01 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

7 Replies
1071 Views

Similar Articles

[PageSpeed] 22

RJ wrote:
> [...] Do I need
> to retrieve the create dates one at a time (using foreach or for) based on 
> the results of GetFiles?

Well, you'd need a loop just to check the information, one way or the other.

In any case, no…you don't necessarily need to retrieve the creation 
timestamp one at a time.  You've probably already noticed the 
appropriate methods in the System.IO.File class to get the information 
you want.  But, if you start with a DirectoryInfo object instead of 
using the Directory class, the GetFiles() method returns an array of 
FileInfo objects.  You can simply get the other information from the 
properties on the FileInfo.

Note of course that there's really not much practical difference between 
the two approaches.  FileInfo will still have to do the same basic file 
system i/o operation to get the information as the equivalent File 
method call would.

FileInfo is useful if you intend to retrieve a number of different 
pieces of information about a file, or intend to inspect that 
information multiple times.  But otherwise, you might as well just call 
the appropriate File method (GetCreationTime() or GetCreationTimeUtc()).

Finally, note that the single-argument overload to Directory.GetFiles() 
is equivalent to passing "*" or "*.*" as the search pattern to the 
two-argument overload.  If you're not actually providing a specific 
pattern to match, you might as well not pass a pattern.

Pete
0
Peter
1/4/2010 9:41:56 PM
=?Utf-8?B?Uko=?= <RJ@discussions.microsoft.com> wrote in
news:8FFFE694-4A8C-460B-985D-7883782C29D9@microsoft.com: 

> Long time developer / total newbie @ C#.
> 
> I want to retrieve a list of files AND the file create date and load
> them into an array for further processing� �
> 
> I found the following which works well 
> Directory.GetFiles(sourceDir, "*.*"
> 
> But I can� Tt find anything similar to file and file create dates.  Do
> I need to retrieve the create dates one at a time (using foreach or
> for) based on the results of GetFiles?

DirectoryInfo directory = new DirectoryInfo(directoryPath);

foreach(FileInfo file in directory.GetFiles())
{
    string name = file.Name;
    string fullPath = file.FullName;
    string directoryPath = file.DirectoryName;\
    string extension = file.Extension;

    //NOTE: each of these has a Utc variation
    //      useful for comparing on directories across the world
    DateTime creationDateTime = file.CreationTime;
    DateTime lastAccessDateTime = file.LastAccessTime;
    DateTime lastWriteDateTime = file.LastWriteTime;
    long lengthInBytes = file.Length;

    //Load to your favorite collection object here
}

Peace and Grace,

-- 
Gregory A. Beamer (MVP)

Twitter: @gbworld
Blog: http://gregorybeamer.spaces.live.com

*******************************************
|      Think outside the box!             |
*******************************************
0
Gregory
1/4/2010 10:05:20 PM
On 2010-01-04, RJ <RJ@discussions.microsoft.com> wrote:
> Long time developer / total newbie @ C#.
>
> I want to retrieve a list of files AND the file create date and load them 
> into an array for further processing?
>
> I found the following which works well 
> Directory.GetFiles(sourceDir, "*.*"
>
> But I can?t find anything similar to file and file create dates.  Do I need 
> to retrieve the create dates one at a time (using foreach or for) based on 
> the results of GetFiles?
>

DirectoryInfo.GetFiles - it returns an array of FileInfo objects, containg the
information yoru after:

DirectoryInfo directory = new DirectoryInfo(sourceDir);
FileInfo[] files = directory.GetFiles();


-- 
Tom Shelton
0
Tom
1/4/2010 10:50:17 PM
Thank you all for your help!  Gregory your post was quite helpful and after 
playing around with your detailed suggestion I learned many things!

Thanks again everyone.

"Gregory A. Beamer" wrote:

> =?Utf-8?B?Uko=?= <RJ@discussions.microsoft.com> wrote in
> news:8FFFE694-4A8C-460B-985D-7883782C29D9@microsoft.com: 
> 
> > Long time developer / total newbie @ C#.
> > 
> > I want to retrieve a list of files AND the file create date and load
> > them into an array for further processingƒ Ý
> > 
> > I found the following which works well 
> > Directory.GetFiles(sourceDir, "*.*"
> > 
> > But I canƒ Tt find anything similar to file and file create dates.  Do
> > I need to retrieve the create dates one at a time (using foreach or
> > for) based on the results of GetFiles?
> 
> DirectoryInfo directory = new DirectoryInfo(directoryPath);
> 
> foreach(FileInfo file in directory.GetFiles())
> {
>     string name = file.Name;
>     string fullPath = file.FullName;
>     string directoryPath = file.DirectoryName;\
>     string extension = file.Extension;
> 
>     //NOTE: each of these has a Utc variation
>     //      useful for comparing on directories across the world
>     DateTime creationDateTime = file.CreationTime;
>     DateTime lastAccessDateTime = file.LastAccessTime;
>     DateTime lastWriteDateTime = file.LastWriteTime;
>     long lengthInBytes = file.Length;
> 
>     //Load to your favorite collection object here
> }
> 
> Peace and Grace,
> 
> -- 
> Gregory A. Beamer (MVP)
> 
> Twitter: @gbworld
> Blog: http://gregorybeamer.spaces.live.com
> 
> *******************************************
> |      Think outside the box!             |
> *******************************************
> .
> 
0
Utf
1/5/2010 3:10:01 PM
=?Utf-8?B?Uko=?= <RJ@discussions.microsoft.com> wrote in
news:D1764F2D-107B-49FF-929F-C131BE8B17F3@microsoft.com: 

> Thank you all for your help!  Gregory your post was quite helpful and
> after playing around with your detailed suggestion I learned many
> things! 

The MSDN library can be your best friend if you like epiphanies. :-)

Peace and Grace,

-- 
Gregory A. Beamer (MVP)

Twitter: @gbworld
Blog: http://gregorybeamer.spaces.live.com

*******************************************
|      Think outside the box!             |
*******************************************
0
Gregory
1/5/2010 3:48:36 PM
I posted a thank you response but it never showed up.  So here we are again.

Thanks to you all for the detailed responses.  I learned many things on this 
somewaht trivial problem.

Thanks again, 
RJ

"Gregory A. Beamer" wrote:

> =?Utf-8?B?Uko=?= <RJ@discussions.microsoft.com> wrote in
> news:8FFFE694-4A8C-460B-985D-7883782C29D9@microsoft.com: 
> 
> > Long time developer / total newbie @ C#.
> > 
> > I want to retrieve a list of files AND the file create date and load
> > them into an array for further processingƒ Ý
> > 
> > I found the following which works well 
> > Directory.GetFiles(sourceDir, "*.*"
> > 
> > But I canƒ Tt find anything similar to file and file create dates.  Do
> > I need to retrieve the create dates one at a time (using foreach or
> > for) based on the results of GetFiles?
> 
> DirectoryInfo directory = new DirectoryInfo(directoryPath);
> 
> foreach(FileInfo file in directory.GetFiles())
> {
>     string name = file.Name;
>     string fullPath = file.FullName;
>     string directoryPath = file.DirectoryName;\
>     string extension = file.Extension;
> 
>     //NOTE: each of these has a Utc variation
>     //      useful for comparing on directories across the world
>     DateTime creationDateTime = file.CreationTime;
>     DateTime lastAccessDateTime = file.LastAccessTime;
>     DateTime lastWriteDateTime = file.LastWriteTime;
>     long lengthInBytes = file.Length;
> 
>     //Load to your favorite collection object here
> }
> 
> Peace and Grace,
> 
> -- 
> Gregory A. Beamer (MVP)
> 
> Twitter: @gbworld
> Blog: http://gregorybeamer.spaces.live.com
> 
> *******************************************
> |      Think outside the box!             |
> *******************************************
> .
> 
0
Utf
1/5/2010 4:41:02 PM
=?Utf-8?B?Uko=?= <RJ@discussions.microsoft.com> wrote in
news:67EFB291-CF9C-464B-8A11-8984654A4E1E@microsoft.com: 

> I posted a thank you response but it never showed up.  So here we are
> again. 
> 
> Thanks to you all for the detailed responses.  I learned many things
> on this somewaht trivial problem.

I saw the response. Depending on your client, it may be an issue with 
how the responses show up. If from a web forum, it takes a bit to fully 
sync.

Peace and Grace,

-- 
Gregory A. Beamer (MVP)

Twitter: @gbworld
Blog: http://gregorybeamer.spaces.live.com

*******************************************
|      Think outside the box!             |
*******************************************
0
Gregory
1/5/2010 6:59:35 PM
Reply:

Similar Artilces:

formatting dates by year #2
I would like to know if there is a way to format dates so that they are formatted by year only. For example, if I click on Format -> Cells, there are a bunch of options, but none of them list to show the year only, just mm/dd/yy or mm/yy, etc. I am trying to create a chart so that only the year shows up. Also, I have tried doing Custom->and "yyyy" in type, but only 1 specific year shows up (i.e. 1905) for all the values. I would like to keep my values. Thanks much! ...

find action on log file
Hello there I want to use outside tool to find who made some update on table in my server I know that there are many tools for this. But can they do it on simple recovery model? Roy Goldhammer (royg@yahoo.com) writes: > I want to use outside tool to find who made some update on table in my > server > > I know that there are many tools for this. But can they do it on simple > recovery model? No. If you are using the simple recovery model, the contents of the log is wasted away everyonce in a while. Well, if the disk area has not been overwritten...

circular files; iterating to a "correct" solution
I am working with a circular file. I have been making changes to the file, and I have noticed at times when i manually calculate that the file iterates to an obviously "incorrect" solution. No amount of changing the max no of iterations or the max change seems to fix the problem. It iterates to the same "incorrect" solution every time. It is like it is stuck in a rut and can't get out. I have also noticed that, if I manually calculate each worksheet separately (that is, hit shift - f9 simulaneously on each worksheet individually, from left to right) all the ...

Autonumber created.. problems in the future?
I managed to create an autonumber in Microsoft CRM. I did this by making a field "Number"(in the database "New_Number") and I published it on the form. Then I went To the SQL server and I changed the field in the table to Identity Yes, Identity seed 1, Identity Increment 1. I locked the field on the form. It worked! I think that this is not supported by Microsoft. But has anybody got any idea which troubles i could get with this configuration? San ________________________________ Do you know all add-ons for Microsoft CRM? Visit http://www.pimpmycrm.com The biggest dange...

File size #11
I have read the other discussions on file sizes but they do not seem to address my problem. I have an Excel file that is 12mb large with low-res jpegs in it. This file also has merged cells to make it look pretty. Does Excel look at these merged cells as graphics? Is this why they are too big? I have run a macro to make sure that it goes to the last cell. How can I get the file smaller? How big are the graphics? If you remove them from the file, what is the size of the file and what is the size of the graphic files? To be sure you do not have extra formatting, if you open the file...

Maximum file sizes
Is there a recommended maximum file size for Excel 2000. PC spec 2Ghz P4 with 256 Mb Any advice appreciated Deus -------------- Does Not Exist Hi have a look at http://www.decisionmodels.com/memlimits.htm -- Regards Frank Kabel Frankfurt, Germany "Deus DNE" <deus.dne@ntlworld.com> schrieb im Newsbeitrag news:1561701c41d4f$358950f0$a001280a@phx.gbl... > Is there a recommended maximum file size for Excel 2000. > > PC spec 2Ghz P4 with 256 Mb > > Any advice appreciated > > Deus > -------------- > Does Not Exist ...

POST or GET?
(apologies if this is OT but I couldn't find an HTTP newsgroup) I am writing an MFC client application which speaks to an HTTP server. The server will send text data to the client, the client will modify and return that data to the server along with a small amount of new data. Should I use GET or POST to get the data from the server? "Richard" <richard@hello.com> wrote in message news:zWudf.14758$Cq4.8824@newsfe7-gui.ntli.net... > I am writing an MFC client application which speaks to an HTTP server. The > server will send text data to the client, the client...

How to repair a .dll file in IE8
Several days ago I noticed in my Dependency Walker that the IESHIMS.dll files has a yellow circle with a question mark on it. What does this mean and How do I repair it? OS: Windows Vista Home Premium Browser Internet Explorer 8 -- TW Hi, See the History tab on that dialog. A web search for ieshims.dll files will also help you find a solution for that file. Regards. "TW" <TW@discussions.microsoft.com> wrote in message news:63E61463-D766-4ABC-B081-BFA8C04FB159@microsoft.com... > Several days ago I noticed in my Dependency Walker that the IESHIMS....

Using Relative path for XML data file?
Is there a way to specify a relative path to an XML data file imported into Excel 2003? I am writing a web app that generates report data as XML for the user to download to their local machine. This data is to be consumed by an Excel reporting spreadsheet, which contains display-formatted tables and charts that are mapped to various data fields in an XML Map, which is in turn linked to the xml data file they will download. The idea is the user only needs to download the data for updates, not the whole spreadsheet. However, since I cannot predict the path where the user will store their...

unsolicited entry in the folder "Temporary Internet Files"
Hello, I am working on a programme which browses web sites and runs under XP. The http download is as follows: pServer = Isession -> GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwStatusCode); if(dwStatusCode == 200) { pFile -> QueryInfo(HTTP_QUERY_LAST_MODIFIED, &sysT); status.lastMod = sysT; if(DBlastMod == status.lastMod) //URL content has not changed since the last visit ...

Need Help, Task Start Date is wrong
I’m using MS Project 2007, have several task linked with finish to start. I have set date to schedule from, hours per day set to 8 and Working Monday thru Friday. My schedule shows Task 1 Duration 4 days, start Wed 6/2/10, Finish Mon 6/7/10 Task 2 Duration 3 days, start Mon 6/7/10, Finish Thu 6/10/10 Task 2 should have a Start Date of 6/8/10 not 6/7/10; what is causing this? Thanks in advance for your help. ...

Linking files 2 ways
I have a work book that is linked to another and vise versa. As thus: Workbook A is where the input of data is made; Workbook B has a link to the input from workbook A; Workbook A retrieves the altered data back as a link. Although this all works fine with both books open, I note that if I open workbook A by itself, that the data it retrieves from Workbook B is not updated . If However, both books are open, there's no problem. I thought linked books were updated automatically if the Update remote references has been selected?? But it appears that the second book is not updated until it ...

OL2007 not move big files from outbox to sent
Hi, We have 2 computers with separate email accounts on Roadrunner. One machine has XP with Outlook 2002-sp3 and works without any problems. The other has Outlook 2007 on Vista and has problems sending files over a meg or so in size. It seems to actually send the file but the file remains in the outbox folder and does not move it to the sent folder. I say it "seems" to send the file because some people complain of getting muliple copies and others don't seem to get them at all. If I hit send again (not set up for auto send) it seems to send the file again (why some ...

explanation of codes in Visual Basic when creating User form
Hi, I am trying to create a user form in Visual Basic however I'm trying to teach myself by reading/watching tutorials. (www.contectures.o.ca, etc) A lot of the instructions I am seeing simply give the code rather than explain how to actually write one from scratch. So... I need to know what each 'term' means so I can understand how the codes work. Any help is much appreciated :) One of the first codes is for the Add button Private Sub cmdAdd_Click() Dim iRow As Long Dim ws As Worksheet Set ws = Worksheets("PartsData") What d...

Certain Keys/Characters not recognised when creating a task
I've just attempted to create a task and the edit control for the subject of the task refused to accept the characters c h s t u and v. I was able to switch to other applications such as a command prompt and internet explorer and type the characters quite happily (so there is nothing wrong with the keyboard) but when I switch back to Outlook it will not recognise them. I'm using Outlook2003 as installed with Office 2003 Professional (SP1 and all other updates applied). As a last resort I closed down Outlook and restarted the program which is now accepting the keys/characters. A...

Show date, time & day of week in one cell
Can I show the date, time and day of week in one cell. I have: 09/03/07 8:30 AM in one cell using the format (Format/Cells/Custom): [$-409]mm/dd/yy h:mm AM/PM;@ Excel refuses to accept ddd for Mon or dddd Monday at the end of the format I want it to read: 09/03/07 8:30 AM Monday in 1 cell. I have Excel 2003. One way: mm/dd/yy h:mm AM/PM dddd;@ In article <Xns99B8A3CAF9130pencilunlistedcom@208.49.82.220>, Burp <burp@beep.comINVALID> wrote: > Can I show the date, time and day of week in one cell. > > I have: > 09/03/07 8:30 AM > in one cell using the for...

How to automate increasing the form cache registry/file etc...
I want to roll out a batch file to make a number of tweaks to CRM The body of it would go REGEDIT /S Kerberosefix.reg REGEDIT /S ForceFormreload.reg REGEDIT /S OutlookFix.reg It would also rename OSA.exe to OSA.bad Remove OSA.exe From the startup menu I need help finding a way to use my batch file to increase the Outlook Form cache from the default 4MB to 50 MB.. This makes CRm more stable and faster for communications. I dont want to manually do this, as it time consuming, are my end users would not be reliable in doing it themselves. I also want to make another batch file or button that...

get a result of an sql into a field
Hi there I would like to get a result of an sql execution (ms sql server) into aq filed. example i A1 I have a ID number in A2 I would like to get the result of something like this 'select name from address where id=A1' Does this exist in Excel ? Thanks in advance Ralf Here is the sub i have written for loading an Sql Query into th worksheet. Parameters: Server Name DataBase Name SQL Command Target Sheet name Column to begin from Row to begin from ex: CALL LoadData("MyServer","MyDataBase","Select UserName fro TblNames", "QueryData"...

How to create an autonumber field?
hi i need to create an autonumber field to automate account numbering. how can i do this? thanx You can do this using a post callout piece of code so when you update an account this code is called which calls back into the platform and works out the last account number then adds one to it and updates the account record. look on msdn.microsoft.com under crm for examples -- John O'Donnell Microsoft CRM MVP http://www.mscrmfaq.us "Max" <Max@discussions.microsoft.com> wrote in message news:0ABFF244-EC0A-48EC-9E76-7CA61E6EBC3A@microsoft.com... > hi > > i need ...

Cannot open Outlook, keep getting Send error report of Microsoft.
We are having problems with Outlook 2003. Everytime we try to open, we get this: Send error report to Microsoft. Any ideas why? All windows and office update have been completed. ...

CSV Files and VLOOKUP error
Does anyone know why VLOOKUP and Compare formulas don't work o information originating from a CSV file? I've tried copying an pasting values only (to leave behind any formatting), but it doesn' help. Through countless tests, I've narrowed it down to the CSV file bein the only possible cause -- Message posted from http://www.ExcelForum.com Hi ajpowers, Just a guess but the imported data may have leading or trailing spaces or are numbers stored as text. You could use the formula =A1=D1 to see if you get a true or false, where A1 is the lookup value and D1 ia the CVS valu...

Recreating site/directory connectors on 2003?
Just got the first 2003 server up and running. We have a single domain, and two sites/admin groups. SiteA contains the current 5.5 server (ServerA) and the new 2003 server (ServerB). SiteB contains a single 5.5 server (ServerC). There is a site connector created under 5.5 between SiteA and SiteB with ServerA and ServerC as the bridgeheads in each site. There is also a directory replication connector between SiteA and SiteB, again with ServerA and ServerC as the bridgeheads in each site. The ADC is installed and working with the default mailbox/public folder CA's for both SiteA ...

is PHStat available and if so how do I get to it
I need help asap Tamika - > I need help asap < PHStat is Prentice Hall's statistical add-in for Excel. It's usually on the CD that's included with the textbook. For more info, try www.prenhall.com/phstat - Mike www.mikemiddleton.com ...

Problem with named range for a large spreadsheet in Excel 2007
Hello, I am trying to generate a large Excel spreadsheet apprx. 10000 rows and 40 columns. I am generating defined name section in the Workbook.xml part of the XLSM package. Here is a sample entry from that section <definedName name="_._44802_._0_._0_._0_._top_line" localSheetId="0" hidden="1">Sheet1!$B$2</definedName> Although the generation goes fine, I can not open the spreadsheet as the Excel throws an error message saying the package is corrupt. But this is not the case if the spreadsheet is small say, 200 rows by 10 columns. ...

How do I get Excell to sort dates that range from 1800 to 1900's
I have posted a cemetery survey on Excell spreadsheet. When I try to sort the birth dates or death dates in ascending or descending order the range of 1900 dates will sort but the 1800 dates fall after the 1900 and will not sort. Why? Is this inherit with this program? The WinXL default dates start with 31 December 1899, so earlier "dates" are interpreted as Text. You can use helper columns and text functions (LEFT(),RIGHT(),MID()) to put the Year, Month and Day in separate columns, then sort. Take a look here for additional workarounds: http://j-walk.com/ss/excel/files...