I had an idea to write some useful code so that the recently downloaded temp files like installation files and other media files can be copied to somewhere safe location before it gets deleted.
string dir = "c:\\Users\\neal\\appdata\\Local\\Temp";
string newdir = "D:\\";
var directory = new DirectoryInfo(dir);
var myFile = (from f in directory.GetFiles()
orderby f.LastAccessTime descending
select f).First();
var myDir = (from f in directory.GetDirectories()
orderby f.LastAccessTime descending
select f).First();
myFile.CopyTo(newdir, true);
The above method doesn't actually work. And I'm not sure why. I guess every file may not have access rights (installation files).
Any idea or any other logic out there?
I definitely agree that there are already proven solutions to this, however if you wish to implement something in code you should check out the FileSystemWatcher http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx
This will notify your program of changes to the directory you are watching so you can take action.
Related
I am creating a Windows application in which on a button click it will check a folder specified in the .config file for '.SQL' files and if it has any files then the application will execute the SQL file in the specified DB.
So for checking the '.sql' file in a directory I used the below code:
DirectoryInfo d = new DirectoryInfo(path);
FileInfo[] sqlfiles = d.GetFiles("*.sql");
Now, I want to add an IF condition to check any such file exist, if not I want to place a warning message.
So could you please help me to find how to check whether any such '.sql' file exist in that directory using the above code?
You can use .Any() to check if any array, or list, or IEnumerable has items. IMO it's a much clearer intent than list.Count > 0.
DirectoryInfo d = new DirectoryInfo(path);
FileInfo[] sqlfiles = d.GetFiles("*.sql");
if(sqlFiles.Any())
{
// At least one .sql file exists
}
else
{
// No sql files exist
}
(Cue arguments about iterators etc.)
I have a root directory and inside that further directories are there. These directories contains various Html and ncx files. I have to get the name of the file that has been last modified.
I am using this code
string filePath = #"~\FolderName\";
string completeFilePath = Server.MapPath(filePath);
var directory = new DirectoryInfo(completeFilePath);
var fileName = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
lblDisplayFileName.Text=fileName.ToString();
But it is only searching files that are placed only in root directory. It is not searching files that are present further in directories of root directory. I don't know how to get last modified filename of the files that are present further in nested directories. I have to display the name of file that has been last modified from all of the files irrespective of present in any directory.
Have a look at the documentation of DirectoryInfo.GetFiles:
MSDN:
Returns a file list from the current directory.
You have to use the overload that takes a SearchOption:
directory.GetFiles("*.*", SearchOption.AllDirectories)
Try the overload of GetFiles which takes 2 parameters
from f in directory.GetFiles(".", SearchOption.AllDirectories)
SearchOption specifies whether the search operation should include only the current directory or all subdirectories.
How can i search for files with particular extension, the search should be carried out through all the logical drives availbale in my computer.
i tried like
var di = new Directoryinfo(" somepath");
Files = di.GetFiles("*.txt");
But my problem is search should carried out in Each and every folder.
Thank you,
Doesn't DirectoryInfo.GetFiles() contain an overload which has 'recursive/include subfolders'
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.getfiles.aspx
Looks like it!
Use
List<string> lst = new List<string>();
foreach(var drive in DriveInfo.GetDrives())
{
if(drive.DriveType == DriveType.Fixed)
lst.Concat(Directory.GetFiles(drive.RootDirectory.FullName, "*.txt",
SearchOption.AllDirectories).ToList());
}
Note: If you find files in all directories, it can give you Access Denied error.
Files = di.GetFiles("*.txt", SearchOption.AllDirectories);
Currently my application uses string[] subdirs = Directory.GetDirectories(path) to get the list of subdirectories, and now I want to extract the path to the latest (last modified) subdirectory in the list.
What is the easiest way to accomplish this?
(efficiency is not a major concern - but robustness is)
Non-recursive:
new DirectoryInfo(path).GetDirectories()
.OrderByDescending(d=>d.LastWriteTimeUtc).First();
Recursive:
new DirectoryInfo(path).GetDirectories("*",
SearchOption.AllDirectories).OrderByDescending(d=>d.LastWriteTimeUtc).First();
without using LINQ
DateTime lastHigh = new DateTime(1900,1,1);
string highDir;
foreach (string subdir in Directory.GetDirectories(path)){
DirectoryInfo fi1 = new DirectoryInfo(subdir);
DateTime created = fi1.LastWriteTime;
if (created > lastHigh){
highDir = subdir;
lastHigh = created;
}
}
Try this:
string pattern = "*.txt"
var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern)
orderby f.LastWriteTime descending
select f).First();
http://zamirsblog.blogspot.com/2012/07/c-find-most-recent-file-in-directory.html
Be warned: You might need to call Refresh() on your Directory Info object to get the correct information:
e.g. in Laramie's answer you'd edit to:
DirectoryInfo fi1 = new DirectoryInfo(subdir);
fi1.Refresh();
DateTime created = fi1.LastWriteTime;
Otherwise you might get outdated info like I did:
"Calls must be made to Refresh before attempting to get the attribute
information, or the information will be outdated."
http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.refresh(v=vs.71).aspx
You can use Directory.GetLastWriteTime (or Directory.GetLastWriteTimeUtc, it doesn't really matter in this case when you're just doing relative comparisons).
Although do you just want to look at the "modified" time as reported by the OS, or do you want to find the directory with the most recently-modified file inside it? They don't always match up (that is, the OS doesn't always update the containing directory "last modified" time when it modifies a file).
If you are building a windows service and you want to be notified when a new file or directory is created you could also use a FileSystemWatcher. Admittedly not as easy, but interesting to play with. :)
IT has been tasked with reducing the file-server usage rate so I'd like to do my part my compressing old files(ie Excel/Access/Txt).
We have some folders that contain thousands of files so I don't want to just zip the whole directory into one large file - it would be preferrable to have a number of smaller files so that it would be easier for a user to find the data 'bucket' they are looking for.
Is there a way using C# to read through a directory and zip the files into year-month groups (all files from year-month placed together in one zip)?
Or would it be better to use a script like AutoIT?
Or are there programs already existing to do this so I don't have to code anything?
Im not sure if your question is about zipping, selecting files from particular year/month or both.
About zipping Peter already mentioned 7-zip and SharpZipLib. I have personally only experience with the latter but its all positive, easy to work with.
About grouping your files it could be done by iterating all the files in the folder and group them by either there created date or last modified date.
pseudo:
var files = new Dictionary<DateTime, IList<string>>();
foreach (var file in Directory.GetFiles(...)) {
var fi = new FileInfo(file);
var date = fi.CreatedDate();
var groupDate = new DateTime(date.Year, date.Month);
if (!files.ContainsKey(groupDate)) files.Add(groupDate, new Collection<string>());
files[groupDate].Add(file);
}
now your should have a dictionary containing distinct year/month keys and foreach key a list of files belonging to that group. So for zipping
pseudo:
foreach (var entry in files) {
var date = entry.Key;
var list = entry.Value;
// create zip-file named date.ToString();
foreach (var file in list) {
// add file to zip
}
}
Surely you can do this with a bit of C# and libraries like 7-zip or SharpZipLib.
You could use System.IO.Directory.GetFiles() to loop through the files on each directory, parsing out by file name and adding them to a 7-zip or SharpZipLib object. If it's thousands of files it might be best to throw it in a service or some kind of scheduled task to run overnight so as not to tax the fileshare.
Good luck to you !
EDIT: As an addendum you could use a System.IO.FileInfo object for each file if you need to parse by created date or other file attirbutes.