Finding the latest written document in a directory
I am working on a BizTalk test system within TFS for a client. They are sending the output messages to a file location and using a GUID as the file name. They have a requirement to take the output message and compare it to a known good output to determine if they are the same or not.
Since we don't know the name of the file we needed something to use to find the file. Unfortunately, we did have anything in the file itself to correlate on nor could we add anything. So, we decided that we would take the last written file in the output directory. I thought there must be some code snippet that someone has already created to do this and to my surprise I couldn't find one. Now there is.
I grab the files in the directory and add them to a SortedList with the DateTime as the key and the full path and file name as the value. I then take the one at the top of the list and use that. The code is below:
XmlDocument outputDocument = new XmlDocument();
string outputDocumentFilePath;
DirectoryInfo dir = new DirectoryInfo(outputLocation);
SortedList sl = new SortedList();
foreach (FileInfo fi in dir.GetFiles())
{
String fname = fi.Name;
DateTime dt = fi.LastWriteTime;
sl.Add(dt,fi.DirectoryName + @"\" + fname);
}
//Read the output document from the Orchestration found in the output directory
outputDocumentFilePath = sl.GetByIndex(sl.Count -1).ToString();
outputDocument.Load(outputDocumentFilePath);
There are a couple of potential issues. What happens if more than one person is testing and multiple people are looking for their output file? What happens if BizTalk takes longer to process the message and you read the latest file before BizTalk writes out the file?
These are outside the scope of this entry - remember, this was just going to be how to grab the last written file in a directory of output files.
Comments
- Anonymous
December 11, 2007
PingBack from http://msdnrss.thecoderblogs.com/2007/12/12/finding-the-latest-written-document-in-a-directory/