I want to reverse the result displayed in a Combobox.
The last saved file would appear first, currently it is the opposite. it appears with this code:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
foreach (string file in files)
{
comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}
According to my research, the solution would be:
.OrderByDescending(p => p.CreationTime).ToArray();
added somewhere. But I don't know. Every attempt I've made has been unsuccessful.
Currently:
101-00.06.52.TXT
101-00.06.54.TXT
101-00.06.56.TXT
Desired outcome:
101-00.06.56.TXT
101-00.06.54.TXT
101-00.06.52.TXT
Does anyone know?
Instead of static method Directory.GetFiles() method, use GetFiles() method from DirectoryInfo class. Apply OrderByDescending() on it.
Directory.GetFiles():
Returns the names of files that meet specified
criteria
Vs
DirectoryInfo.GetFiles():
Returns a file list from the current directory.
Like,
DirectoryInfo di = new DirectoryInfo(#"C:\Test\"); //Get the Directory information
var allTxtFiles = di.GetFiles("*.txt") //Get all files based on search pattern
.OrderByDescending(p => p.CreationTime) //Sort by CreationTime
.Select(x => x.Name); //Select only name from FileInfo object
foreach (string file in allTxtFiles)
{
comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
}
I don't know the reason why you problem. But if you want to receive correct result is simple. First try this:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
comboBox1.ItemsSource = files;
if the result is not correct. Use this:
string[] files = Directory.GetFiles(#"C:\Test\",*.TXT");
files = files.Reverse();
comboBox1.ItemsSource = files;
I am trying to rename multiple files in C# after specific character.
In my folder I have these files:
Application.xml.4589.done
Compatible.xml.8790.done
I want to rename these files like below:
Application.xml
Compatible.xml
Basically after .xml I am looking to remove everything.
Here is the code I am trying:
public static void Main(string[] args)
{
DirectoryInfo d = new DirectoryInfo(#"C:\Test\");
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
{
var extension = f.FullName.Substring(f.FullName.LastIndexOf('.'), f.FullName.Length - 20);
// Need help here
}
}
Can anybody help me with that?
Thanks
You can Split string by . and Take the first two elements from the split array and Join as a string. You will get the desire file name with an extension.
//I showed you minimal example to solve your problem, update your code accordingly.
var infos = new List<string>(){"Compatible.xml.8790.done", "Compatible.xml.8790.done"};
foreach (var f in infos)
{
var newFileName = string.Join(".", f.Split('.').Take(2));
Console.WriteLine(newFileName);
}
Try Online
I have a text file that has a string like:
"•5•Enter Title Name•Enter Description Here•30/04/2015•UNFINISHED•"
I am reading this text file in, how can I write it so the items between the • are put in seperate variables or strings. I have a general idea, using foreach loops with an if statement that checks for the specific character. Can anybody help me please? (code so far is below)
MessageBox.Show("Opening saved file: TaskFile.txt");
string path1 = (#"TaskFile.txt");
string lineOfText = File.ReadAllText(path1);
System.Diagnostics.Debug.WriteLine(lineOfText);
foreach (var sItem in lineOfText)
{
if(sItem == '•')
{
System.Diagnostics.Debug.WriteLine("test");
}
}
You can use Split method and use it like this
List<string> list = sItem.Split('.').ToList();
I agree with Ehsan on the Split method, but I think it should be like this:
var arrayOfStrings = lineOfText.Split('•');
foreach (var str in arrayOfStrings)
{
//do something.
}
to get all the files, which contains CustsExportin its name, in a folder I do this:
foreach (string file in Directory.EnumerateFiles(xmlFolder, "*CustsExport*.xml"))
but there is a case where I don't want to extract the file that its name ends with Empty like this:
Erb3PCustsExport-303_20080319_063109_000_Empty
Could you help me please?
Many thanks
With LINQ-power and System.IO.Path.GetFileNameWithoutExtension:
foreach (string file in Directory.EnumerateFiles(xmlFolder, "*CustsExport*.xml")
.Where(fn => !Path.GetFileNameWithoutExtension(fn).EndsWith("Empty")))
{
// ...
}
I have a Folder which has multiple sub folders. Each sub folder has many .dot and .txt files in them.
Is there a simple solution in C# .NET that will iterate through each file and check the contents of that file for a key phrase or keyword?
Document Name Keyword1 Keyword2 Keyword3 ...
test.dot Y N Y
To summarise:
Select a folder
Enter a list of keywords to search for
The program will then search through each file and at the end output something like above, I am not to worried about creating the datatable to show the datagrid as I can do this. I just need to perform the find in files function similar to Notepad++'s find in files option
Thanks in advance
What you want is recursively iterate files in a directory (and maybe it's subdirectories).
So your steps would be to loop eeach file in the specified directory with Getfiles() from .NET. then if you encounter a directory loop it again.
This can be easily done with this code sample:
public static IEnumerable<string> GetFiles(string path)
{
foreach (string s in Directory.GetFiles(path, "*.extension_here"))
{
yield return s;
}
foreach (string s in Directory.GetDirectories(path))
{
foreach (string s1 in GetFiles(s))
{
yield return s1;
}
}
}
A more indepth look on iterating throug files in directories in .NET is located here:
http://blogs.msdn.com/b/brada/archive/2004/03/04/84069.aspx
Then you use the IndexOf method from String to check if your keywords are in the file (I discourage the use of ReadAllText, if your file is 5 MB big, your string will be too. Line-by-line will be less memory-hungry)
You can use Directory.EnumerateFiles with a searchpattern and the recursive hint(SearchOption.AllDirectories). The rest is easy with LINQ:
var keyWords = new []{"Y","N","Y"};
var allDotFiles = Directory.EnumerateFiles(folder, "*.dot", SearchOption.AllDirectories);
var allTxtFiles = Directory.EnumerateFiles(folder, "*.txt", SearchOption.AllDirectories);
var allFiles = allDotFiles.Concat(allTxtFiles);
var allMatches = from fn in allFiles
from line in File.ReadLines(fn)
from kw in keyWords
where line.Contains(kw)
select new {
File = fn,
Line = line,
Keyword = kw
};
foreach (var matchInfo in allMatches)
Console.WriteLine("File => {0} Line => {1} Keyword => {2}"
, matchInfo.File, matchInfo.Line, matchInfo.Keyword);
Note that you need to add using System.Linq;
Is there a way just to get the line number?
If you just want the line numbers you can use this query:
var matches = allFiles.Select(fn => new
{
File = fn,
LineIndices = String.Join(",",
File.ReadLines(fn)
.Select((l,i) => new {Line=l, Index =i})
.Where(x => keyWords.Any(w => x.Line.Contains(w)))
.Select(x => x.Index)),
})
.Where(x => x.LineIndices.Any());
foreach (var match in matches)
Console.WriteLine("File => {0} Linenumber => {1}"
, match.File, match.LineIndices);
It's a little bit more difficult since LINQ's query syntax doesn't allow to pass the index.
The first step: locate all files. It is easily done with System.IO.Directory.GetFiles() + System.IO.File.ReadAllText(), as others have mentioned.
The second step: find keywords in a file. This is simple if you have one keyword and it can be done with IndexOf() method, but iterating a file multiple times (especially if it is big) is a waste.
To quickly find multiple keywords in a text I think you should use the Aho-Corasick automaton (algorithm). See the C# implementation at CodeProject: http://www.codeproject.com/Articles/12383/Aho-Corasick-string-matching-in-C
Here's a way using Tim's original answer to get the line number:
var keyWords = new[] { "Keyword1", "Keyword2", "Keyword3" };
var allDotFiles = Directory.EnumerateFiles(folder, "*.dot", SearchOption.AllDirectories);
var allTxtFiles = Directory.EnumerateFiles(folder, "*.txt", SearchOption.AllDirectories);
var allFiles = allDotFiles.Concat(allTxtFiles);
var allMatches = from fn in allFiles
from line in File.ReadLines(fn).Select((item, index) => new { LineNumber = index, Line = item})
from kw in keyWords
where line.Line.Contains(kw)
select new
{
File = fn,
Line = line.Line,
LineNumber = line.LineNumber,
Keyword = kw
};
foreach (var matchInfo in allMatches)
Console.WriteLine("File => {0} Line => {1} Keyword => {2} Line Number => {3}"
, matchInfo.File, matchInfo.Line, matchInfo.Keyword, matchInfo.LineNumber);