I am trying to just get the subfoldername and not the FULLNAME into a serparate column in my datatable. Please help.
protected void Page_Load(object sender, EventArgs e) {
DataTable ReportsDT = new DataTable("ReportsDT");
ReportsDT.Columns.Add("Name");
ReportsDT.Columns.Add("FolderName");
DirectoryInfo DirInfo = new DirectoryInfo(Server.MapPath("Reports"));
DataRow ReportDTRow = ReportsDT.NewRow();
foreach (FileInfo fi in DirInfo.GetFiles("*.*", SearchOption.AllDirectories)) {
ReportDTRow = ReportsDT.NewRow();
ReportDTRow["Name"] = fi.Name;
ReportDTRow["FolderName"] = fi.FullName;
ReportsDT.Rows.Add(ReportDTRow);
}
}
You can use DirectoryInfo to get information on a given directory. You have a copy supplied in the FileInfo instance under fi.Directory:
foreach (FileInfo fi in DirInfo.GetFiles("*", SearchOption.AllDirectories)) {
ReportDTRow = ReportsDT.NewRow();
ReportDTRow["Name"] = fi.Name;
ReportDTRow["FolderName"] = fi.Directory.Name;
ReportsDT.Rows.Add(ReportDTRow);
}
See sample code below:
string[] folders = fi.FullName.Split('\\');
string subFolderName = folders[folders.Length - 2];
I believe you are looking for
ReportDTRow["FolderName"] = fi.Directory.Name;
You could also just split the string on the path separator and parse it out yourself, but the above should work nicely assuming I understand what you want.
Related
So I am making a little test, and when using a listbox it says "C:/Test/Text.txt" but I want it to say Text.txt. So I currently have
private void FlatButton3_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string folder = #"C:/Aatrox";
string[] txtfiles = Directory.GetFiles(folder, "*.txt");
string[] luafiles = Directory.GetFiles(folder, "*.lua");
foreach (var item in folder)
{
ListBox1.Items.Add(Path.GetFileName(Convert.ToString(txtfiles)));
}
}
and in the ListBox it says System.String[]
Any help?
If you want both the .lua files and the .txt files (and you are using .NET 4.5 or later) you can use some LINQ to grab the files you want:
ListBox1.Items.Clear();
var files = Directory.EnumerateFiles(#"C:/Aatrox")
.Where(file => file.ToLower().EndsWith("lua")
|| file.ToLower().EndsWith("txt"));
foreach(var file in files)
{
ListBox1.Items.Add(Path.GetFileName(file));
}
It might actually be faster to use a non-LINQ approach like this:
ListBox1.Items.Clear();
foreach(var file in Directory.EnumerateFiles(#"C:/Aatrox"))
{
string extension = Path.GetExtension(file);
if(string.Compare(extension, ".lua", true) == 0
|| string.Compare(extension, ".txt", true) == 0)
{
ListBox1.Items.Add(Path.GetFileName(file));
}
}
Thanks to #maccettura I have got it.
private void FlatButton3_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string folder = #"C:/Aatrox";
string[] txtfiles = Directory.GetFiles(folder, "*.txt");
string[] luafiles = Directory.GetFiles(folder, "*.lua");
foreach (var item in txtfiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
}
You are looping in folder variable and using txtfiles variable instead of item. Also, converting a String to String is useless. Maybe your code shall be like:
private void FlatButton3_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string folder = #"C:/Aatrox";
string[] txtfiles = Directory.GetFiles(folder, "*.txt");
string[] luafiles = Directory.GetFiles(folder, "*.lua");
foreach (var item in txtfiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
}
Extra: if you also want to list *.lua files, you have to do another foreach loop.
This is far from the most efficient answer, but one that will hopefully help you understand.
var filenames = Directory.GetFiles("C:/Aatrox", "*.txt").ToList();
filenames.AddRange(Directory.GetFiles("C:/Aatrox", "*.lua"));
foreach (var filename in filenames)
listBox.Add(Path.GetFileName(filename));
var files = Directory.GetFiles(path, "*.*", SearchOption.Recursive);
var filter = files.Where(file => file.Contains(".txt") || file.Contains(".lua"));
foreach(var file in filter)
listbox.Items.Add(new FileInfo(file).Name);
Code is pretty simple, grab the files within directory, use Linq to filter out the extensions you want. Then loop through, convert to FileInfo to use the Name property that uses the short name.
I would need to fill a datagrid with the values of versioninfo prellevato by a double foreach.
incorro error: FileVersionInfo.GetVersionInfo (file); (incorrect syntax)
DirectoryInfo dir = new DirectoryInfo(#"D:\TEMP\");
foreach (DirectoryInfo folder in dir.GetDirectories())
{
foreach (FileInfo file in folder.GetFiles())
{
FileVersionInfo verInfo = FileVersionInfo.GetVersionInfo(file);
dataGridView1.ColumnCount = 1;
dataGridView1.Columns[0].Name = "Version";
string[] row = new string[] { verInfo.ProductVersion };
dataGridView1.Rows.Add(row);
}
}
As BugFinder already pointed you to the documentation of the method FileVersionInfo.GetVersionInfo
It takes only a string as parameter. So you should give it the filename and not the FileInfo
FileVersionInfo verInfo = FileVersionInfo.GetVersionInfo(file.FullName);
I'm trying to match a file name to a partial string in a List. The list will have something like 192 in it and the matching file will be xxx192.dat. Using .Contains does not match the file name to the string in the List. Can anyone tell me how to get this done or how to use wildcard chars in the contains?
Code below.
// use this to get a specific list of files
private List<string> getFiles(string path, List<string> filenames)
{
List<string> temp = new List<string>();
string mapPath = Server.MapPath(path);
//DirectoryInfo Di = new DirectoryInfo(mapPath);
DirectoryInfo Di = new DirectoryInfo(#"C:\inetpub\wwwroot\Distribution\" + path); // for testing locally
FileInfo[] Fi = Di.GetFiles();
foreach (FileInfo f in Fi)
{
if (filenames.Contains(f.Name)) **// *** this never matches**
temp.Add(f.FullName);
}
return temp;
}
I'v changed the code trying to use the suggestions but it's still not working. I'll add in the data like I'm stepping through the code.
// use this to get a specific list of files
private List<string> getFiles(string path, List<string> filenames)
{
List<string> temp = new List<string>();
string mapPath = Server.MapPath(path);
//DirectoryInfo Di = new DirectoryInfo(mapPath);
DirectoryInfo Di = new DirectoryInfo(#"C:\inetpub\wwwroot\Distribution\" + path); // for testing locally
foreach (string s in filenames) // list has 228,91,151,184 in it
{
FileInfo[] Fi = Di.GetFiles(s); // s = 228: Fi = {System.IO.FileInfo[0]}
foreach (FileInfo f in Fi) //Fi = {System.IO.FileInfo[0]}
{
temp.Add(f.FullName);
}
}
return temp;
}
When I look at the directory where these files are I can see:
pbset228.dat
pbmrc228.dat
pbput228.dat
pbext228.dat
pbget228.dat
pbmsg228.dat
This is working now. It may not be the most efficient way to do this, but it gets the job done. Maybe someone can post a sample that does the same thing in a better way.
// use this to get a specific list of files
private List<string> getFiles(string path, List<string> filenames)
{
List<string> temp = new List<string>();
string mapPath = Server.MapPath(path);
//DirectoryInfo Di = new DirectoryInfo(mapPath);
DirectoryInfo Di = new DirectoryInfo(#"C:\inetpub\wwwroot\Distribution\" + path); // for testing locally
FileInfo[] Fi = Di.GetFiles();
foreach (FileInfo f in Fi)
{
foreach (string s in filenames)
{
if (f.Name.Contains(s))
temp.Add(f.FullName);
}
}
return temp;
}
You can use the Any() LINQ extension:
filenames.Any(s => s.EndsWith(f.Name));
This will return True if any element in the enumeration returns true for the given function.
For anything more complex, you could use a regular expression to match:
filenames.Any(s => Regex.IsMatch(s, "pattern"));
Use the static Directory.GetFiles method that lets you include a wildcards and will be more efficient that retrieving all the files and then having to iterate through them.
Or you can even use DirectoryInfo.GetFiles and pass your search string to that.
Change this
foreach (FileInfo f in Fi)
{
if (filenames.Contains(f.Name)) **// *** this never matches**
temp.Add(f.FullName);
}
return temp;
Into something like this
temp = filenames.Find(file => file.Contains(someNameYoureLookingFor));
I have list all item using foreach by its filename. Now, how can I add in the second column the path of each files listed in the first column? I have already add a column or collection on the properties.
foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
{
string fileName = Path.GetFileName(filePath);
listViewFiles.Items.Add(fileName);
}
Try this:
// Set up List View
listViewFiles.View = View.Details;
listViewFiles.Columns.Clear();
listViewFiles.Columns.Add("File name");
listViewFiles.Columns.Add("File path");
// Populate with files and file paths
foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
{
string fileName = Path.GetFileName(filePath);
listView1.Items.Add(fileName).SubItems.Add(new FileInfo(fileName).DirectoryName);
}
EDIT:
Personally, I find it easier to instantiate a DirectoryInfo for this kind of thing, it populate lots of useful fields for you. So you could do:
DirectoryInfo di = new DirectoryInfo(path);
foreach (FileInfo fi in di.GetFiles(fileType, SearchOption.AllDirectories))
listViewFiles.Items.Add(fi.Name).SubItems.Add(fi.DirectoryName);
If you want to know how you can extract the path (without filename), create a FileInfo object and read out its DirectoryName property:
var fi = new FileInfo(filename);
var dir = fi.DirectoryName;
You can do:
foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
{
string fileName = Path.GetFileName(filePath);
string directoryName = Path.GetDirectoryName(filePath);
listViewFiles.Items.Add(fileName, directoryName);
}
See the ListViewItem constructors for more info.
You can use the SubItems:
foreach (string filePath in Directory.GetFiles(path, fileType, SearchOption.AllDirectories))
{
FileInfo fi = new FileInfo(filepath);
listViewFiles.Items.Add(fi.Name).SubItems.Add(fi.DirectoryName);
}
EDIT: I modify it to have filename and file directory
I create a FileInfo array like this
try
{
DirectoryInfo Dir = new DirectoryInfo(DirPath);
FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo FI in FileList)
{
Console.WriteLine(FI.FullName);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
And this array holds all the file names in folder = DirPath
I thought of looping through the FileInfo array and copy it to a String array. Is this ok or is there a much cleaner method ?
Using LINQ:
FileList.Select(f => f.FullName).ToArray();
Alternatively, using Directory you can get filenames directly.
string[] fileList = Directory.GetFiles(DirPath, "*.*",
SearchOption.AllDirectories);
If you want to go the other way (convert string array into FileInfo's) you can use the following:
string[] files;
var fileInfos = files.Select(f => new FileInfo(f));
List<FileInfo> infos = fileInfos.ToList<FileInfo>();
the linq is a great soluction, but for the persons who don't want to use linq, i made this function:
static string BlastWriteFile(FileInfo file)
{
string blasfile = " ";
using (StreamReader sr = file.OpenText())
{
string s = " ";
while ((s = sr.ReadLine()) != null)
{
blasfile = blasfile + s + "\n";
Console.WriteLine();
}
}
return blasfile;
}
Try this one
DirectoryInfo directory = new DirectoryInfo("your path");
List<string> Files = (directory.GetFiles().Where(file => file.LastWriteTime >= date_value)).Select(f => f.Name).ToList();
If you don't want a filter with date, you can simply convert with the below code
List<string> logFiles = directory.GetFiles().Select(f => f.Name).ToList();
If you need the full path of the file, you can use FullName instead of Name.