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);
Related
I am trying to make a program to backup files from a particular folder, along with the files within the subfolders of the main folder to another backup folder.
This is part of the code I am trying to accomplish the goal, however I am getting backed up only the files from the main folder, and the subfolders are being copied entirely(all of the files in them).
public static string[] Backup(string sourceDirectory, string targetDirectory, string backupDirectory)
{
DirectoryInfo diBackup = new DirectoryInfo(backupDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
List<string> dups = new List<string>();
string[] fileNamesSource = Directory.GetFiles(sourceDirectory, "*", SearchOption.AllDirectories);
string[] fileNamesDest = Directory.GetFiles(targetDirectory, "*", SearchOption.AllDirectories);
List<string> dupNS = new List<string>();
List<string> dupND = new List<string>();
List<string> BCKP = new List<string>();
string replacement = "";
for (int i = 0; i < fileNamesDest.Length; i++)
{
string res = fileNamesDest[i].Replace(targetDirectory, replacement);
dupND.Add(res);
}
foreach (var ns in fileNamesSource)
{
string res = ns.Replace(sourceDirectory, replacement);
dupNS.Add(res);
}
var duplicates = dupND.Intersect(dupNS);
string[] DuplicatesStringArray = duplicates.ToArray();
foreach (var dup in DuplicatesStringArray)
{
string res = targetDirectory + dup;
BCKP.Add(res);
}
string[] ToBeBackedUp = BCKP.ToArray();
Directory.CreateDirectory(diBackup.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in diTarget.GetFiles())
{
if (ToBeBackedUp.Contains(fi.FullName)){
fi.CopyTo(Path.Combine(diBackup.FullName, fi.Name), true);
}
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in diTarget.GetDirectories())
{
if (ToBeBackedUp.Contains(diSourceSubDir.FullName)) {
DirectoryInfo nextTargetSubDir =
diBackup.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
return ToBeBackedUp;
}
Any ideas of how can I copy only the files in the subfolders that exist in the "source" folder?
Also the CopyAll function:
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
Thanks in advance.
You can try this way as
Much easier
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
A simple solution: in your CopyAll method, load the SearchOption.AllDirectories argument to your GetFiles method:
foreach (FileInfo fi in source.GetFiles("*", SearchOption.AllDirectories))
{
fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
}
You can use Directory.GetFiles along with SearchOption.AllDirectories to extract the files from the sub-folders as well:
Directory.GetFiles(path, *search pattern goes here*, SearchOption.AllDirectories)
I have a datagridview
ID Name
-----------
1 ABC
2 DEF
3 XYZ
I have 3 files in a directory
ABC.csv
DEF.csv
XYZ.csv
How do I loop through the file names and rename them according to their ID, so that they become
1.csv
2.csv
3.csv
Here's my code but I do not know to do the retrieve the ID from datagridview. Any help would be much appreciated! Thank you. :)
DirectoryInfo d = new DirectoryInfo(sourceDirCSV);
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
{
try
{
File.Move(f.FullName, f.FullName.ToString().Replace(Path.GetFileNameWithoutExtension(sourceDirCSV), "???"));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I will do something like this:
string sourceDir = "D:\\Temp\\";
DirectoryInfo d = new DirectoryInfo(sourceDir);
string newFileName = "";
string oldFileName = "";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
newFileName = sourceDir + row.Cells["ID"].Value.ToString() + ".csv";
oldFileName = sourceDir + row.Cells["Name"].Value.ToString() + ".csv";
if (File.Exists(oldFileName))
{
File.Move(oldFileName, newFileName);
}
}
You can Try with the Following:
Loop through all rows of DataGrid:
foreach(DataGridViewRow row in DataGridView1.Rows)
{
string colVal=row.Cells(1).Value.ToString();
foreach (string currFilename in Directory.GetFiles(path, "*.csv").Select(Path.GetFileName))
{
//Path.GetFileNameWithoutExtension(fi.Name): this will get file name without extension
if(colVal.Equals(currFilename))
{
//rename file here
}
}
}
Please make changes according to your requirement dont use "as is".
hope this helps you!
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 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.
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.