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
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)
string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry, "*.jpg");
But not only gif i want to specify that also it will be only files that contains the name infrared. For example i have files name 0infrared.gif and also 0visible.gif and i want to get all the files that are infrared.
This will get you all files with infrared in file name and with extension jpg
string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry,
"*infrared*.jpg");
string[] list = Directory.GetFiles(
countriesMainPath + "\\" + currentDownloadCountry,
"*infrared*.*");
This will return all the files contain infrared in their file name.
I think this may be what you look for. ref: MSDN
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
{
string[] searchPatterns = searchPattern.Split('|');
List<string> files = new List<string>();
foreach (string sp in searchPatterns)
files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption));
files.Sort();
return files.ToArray();
}
Usage
var wantedImgs = GetFiles(
dirYouWant, "*infrared*.jpg|*infrared*.gif",
earchOption.TopDirectoryOnly);
string partialName = "infrared";
DirectoryInfo dir = new DirectoryInfo(#"c:\");
FileInfo[] filesInDir = dir.GetFiles("*" + partialName + "*.*");
foreach (FileInfo foundFile in filesInDir)
{
string fullName = foundFile.FullName;
Console.WriteLine(fullName);
}
maybe *infrared*.(jpg|gif) will work
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));
how do i allow this code to retrieve the files from a directory? For example, my directory name is "Folder Name":
private ObservableCollection<FileItem> LoadFiles()
{
ObservableCollection<FileItem> files = new ObservableCollection<FileItem>();
foreach (string filePath in this.Store.GetFileNames())
files.Add(new FileItem { FileName = filePath });
return files;
}
EDIT:
I've tried this, and it still isn't working:
private ObservableCollection<FileItem> LoadFiles()
{
ObservableCollection<FileItem> files = new ObservableCollection<FileItem>();
foreach (string filePath in this.Store.GetFileNames())
files.Add(new FileItem { "FlashCardApp\\" + FileName = filePath });
return files;
}
I've finally found the answer to my own question.
This is how it is suppose to be:
private ObservableCollection<FileItem> LoadFiles()
{
ObservableCollection<FileItem> files = new ObservableCollection<FileItem>();
foreach (string filePath in this.Store.GetFileNames("FlashCardApp\\"))
files.Add(new FileItem { FileName = filePath });
return files;
}
By having \ after the folder name, "FlashCardApp\\", it will retrieve the files from the directory.
DirectoryInfo di = new DirectoryInfo("c:/Folder Name");
FileInfo[] rgFiles = di.GetFiles("*.*");
foreach(FileInfo fi in rgFiles)
{
//Do something
fi.Name
}
To retrieve file names, you can use System.IO:
string[] filePaths = Directory.GetFiles(path, "*.txt")
The Directory class is in System.IO.
I doubth that your folder name is correct. I'll recommend you use storeFile.GetDirectoryNames("*") to see what the correct paths for the directory is.
Microsoft wrote a great example I think you should try and take a look at, since there's nothing obvious wrong with your code.
DirectoryInfo Dir = new DirectoryInfo(Server.MapPath(strheadlinesid));
FileInfo[] FileList = Dir.GetFiles("*.txt", SearchOption.AllDirectories);
In the Place of *.txt ,I want to mention some more file extensions how can I do that.
I used another type of approach but I have a small problem in it when I use the FI as hyperlink it's giving total path.but I want to print only the file name not fullpath.
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.emf,*.xbm,*.ico,*.eps,*.tif,*.tiff,*.g01,*.g02,*.g03,*.g04,*.g05,*.g06,*.g07,*.g08";
foreach (string FI in Directory.GetFiles(Server.MapPath(strheadlinesid), "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
Response.Write("<td><a href= view5.aspx?file=" + strheadlinesid + "\\" + FI + " target=_self;> " +
FI + "</a></td>");
}
Try
string fileFilter = "*.wma,*.jpeg,*.txt";
string[] fileExt = fileFilter.Split(',');
FileInfo[] fileInfo = null;
DirectoryInfo dir = new DirectoryInfo("D:\\Test");
List<FileInfo[]> listFileInfo = new List<FileInfo[]>();
foreach (string strVar in fileExt)
{
fileInfo = dir.GetFiles(strVar, SearchOption.AllDirectories);
listFileInfo.Add(fileInfo);
}