I've come across some strange behavior trying to get files that start with a certain string.
Please would someone give a working example on this:
I want to get all files in a directory that begin with a certain string, but also contain the xml extension.
for example:
apples_01.xml
apples_02.xml
pears_03.xml
I want to be able to get the files that begin with apples.
So far I have this code
DirectoryInfo taskDirectory = new DirectoryInfo(this.taskDirectoryPath);
FileInfo[] taskFiles = taskDirectory.GetFiles("*.xml");
FileInfo[] taskFiles = taskDirectory.GetFiles("apples*.xml");
var taskFiles = taskDirectory.GetFiles("*.xml").Where(p => p.Name.StartsWith("apples"));
Related
I am a newbie to programming so i am hoping support for my problems from all my friends
This is the problem
I have used the loation as 2DB to read a csv file.It works well when I give the file name also But I want to give only location and program needs to select the file
string path = "G:\kaash\2DB\";
string[] row_text = System.IO.File.ReadAllLines(""+path+", *.csv");
string[] data_col = null;
This code will help you to find all .csv files as a list of strings from the specified directory.
string path = #"G:\kaash\2DB\";
List<string> csvIn2DB = System.IO.Directory.GetFiles(path, "*.csv", SearchOption.TopDirectoryOnly).ToList();
By modifying the search pattern you can locate your files more specifically. You can change the SearchOption to AllDirectories if you want to extend the search to inner folders of the specified directory.
Let you need to get all your .csv file names follows the pattern "FILECSV_xxxxxx.csv", then the search pattern will be like this: FILECSV_*.csv
I'm trying to use the Duplicati API to restore a single file.
About the Scenario: The whole thing runs on linux so it is compiled with mono. My backup contains two source Folders, so if I run Interface.ListSourceFolders() I get an Array of two.
Desired result: I want to restore one single file (or Folder) from my backup
Current result: If I run the code below it restores all the backed up files (so Folder 1 and Folder 2) into the path in //Comment1.
List<string> files = new List<string>();
files.Add("path"); //Comment1
Dictionary<string,string> options = new Dictionary<string,string>();
options["passphrase"] = MySettings.Password;
options["restore-time"] = date;
//Comment2
Interface i = new Interface("file:///path/to/archives", options);
string result = i.Restore(files.ToArray());
What I tried: I tried to set the path at //Comment1 to the absolute path (/desired/file/to/restore) or using the index of the source Folder (0/file/to/restore) and I also played around at //Comment2. e.g. I added something like options["restore-path"] = "/path/to/restore". I always get the same result.
Does anyone see what I'm doing wrong? Because I don't know what else I could try. There is almost no documentation so I don't know where to search. If someone knows a link for a good documentation I would be happy too!
In case if someone is interested. After trying around for hours I finally found out how to restore just a single file or folder. Here is what I'm doing now:
List<string> files = new List<string>();
files.Add("/restore/path"); //Comment1
Dictionary<string,string> options = new Dictionary<string,string>();
options["passphrase"] = MySettings.Password;
options["restore-time"] = date;
options["file-to-restore"] = "files"; //Comment2
Interface i = new Interface("file:///path/to/archives", options);
string result = i.Restore(files.ToArray());
At //Comment1 you need to set the desired restore path. In this folder all backup-set-folders are created (The folders from Interface.ListSourceFolders())
At //Comment2 you can specify the files to be restored in this form: 0/file/to/restore where 0 is the index of the source folder (Interface.ListSourceFolders()). If you need to restore multiple files you can do it by combining them into one string: e.g. Windows: 0/file1;1/file2 or Linux 0/file1:1/file2 (The difference is semicolon or colon)
Now there is just one more thing: You can not restore a folder with its files. You need to combine all files and sub-files in the string mentioned above.
I hope I could help somebody.
I need to get the directory name from its path regardless of any of having a trailing backslash. For example, user may input one of the following 2 strings and I need the name of logs directory:
"C:\Program Files (x86)\My Program\Logs"
"C:\Program Files (x86)\My Program\Logs\"
None of the following gives correct answer ("Logs"):
Path.GetDirectoryName(m_logsDir);
FileInfo(m_logsDir).Directory.Name;
They apparently analyze the path string and in the 1st example decide that Logs is a file while it's really a directory.
So it should check if the last word (Logs in our case) is really a directory; if yes, return it, if no (Logs might be a file too), return a parent directory. If would require dealing with the actual filesystem rather than analyzing the string itself.
Is there any standard function to do that?
new DirectoryInfo(m_logsDir).Name;
This may help
var result = System.IO.Directory.Exists(m_logsDir) ?
m_logsDir:
System.IO.Path.GetDirectoryName(m_logsDir);
For this we have a snippet of code along the lines of:
m_logsDir.HasFlag(FileAttribute.Directory); //.NET 4.0
or
(File.GetAttributes(m_logsDir) & FileAttributes.Directory) == FileAttributes.Directory; // Before .NET 4.0
Let me rephrase my answer, because you have two potential flaws by the distinguishing factors. If you do:
var additional = #"C:\Program Files (x86)\My Program\Logs\";
var path = Path.GetDirectoryName(additional);
Your output would be as intended, Logs. However, if you do:
var additional = #"C:\Program Files (x86)\My Program\Logs";
var path = Path.GetDirectoryName(additional);
Your output would be My Program, which causes a difference in output. I would either try to enforce the ending \ otherwise you may be able to do something such as this:
var additional = #"C:\Program Files (x86)\My Program\Logs";
var filter = additional.Split('\\');
var getLast = filter.Last(i => !string.IsNullOrEmpty(i));
Hopefully this helps.
Along the lines of the previous answer, you could enforce the trailing slash like this:
Path.GetDirectoryName(m_logsDir + "\");
Ugly but it seems to work - whether there's 0 or 1 slash at the end. The double-slash is treated like a single-slash by GetDirectoryName.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
GetFiles with multiple extentions
is there a function like GetFiles that takes more then 1 file type like
DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
FileInfo[] rgFiles = di.GetFiles("*.bmp, *.jpg, etc");
AFAIK, this isn't directly possible.
Instead, you can get every file, then filter the array:
HashSet<string> allowedExtensions = new HashSet<string>(extensionArray, StringComparer.OrdinalIgnoreCase);
FileInfo[] files = Array.FindAll(dirInfo.GetFiles(), f => allowedExtensions.Contains(f.Extension));
extensionArray must include . before each extension, but is case-insensitive.
Not that I know of.
I implemented the same problem like so:
DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
FileInfo[] rgFiles = di.GetFiles("*.bmp")
.Union(di.GetFiles("*.jpg"))
.Union(di.GetFiles("etc"))
.ToArray();
Note that this requires the System.Linq namespace.
How to get files with multiple extensions
If you want your code to be bullet proof in the sense your file detection mechanism detects an image file not based on the extension but on the nature of the file, you'd have to to load your files as byte[] and look for a magic trail of bytes usually in the beginning of the array. Every graphical file has it's own way of manifesting itself to the software through presenting that magic value of bytes. I can post some code examples if you'd like.
No, theres not. Windows does not have a way to separate filters in the search pattern.
This could be done manually through LINQ, though.
By using the EnumerateFiles you'll get results as they come back so you don't have to wait for all the files in order to start working on the result.
var directory = new DirectoryInfo("C:\\");
var allowedExtensions = new string[] { ".jpg", ".bmp" };
var imageFiles = from file in directory.EnumerateFiles("*", SearchOption.AllDirectories)
where allowedExtensions.Contains(file.Extension.ToLower())
select file;
foreach (var file in imageFiles)
Console.WriteLine(file.FullName);
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. :)