C# listbox to file listing - c#

What I have is a listbox being populated by a textbox.
I want to search in a specific directory for all files that match the listbox criteria. I want do do this for each listing in the listbox, then I want to copy out all the matching files to another directory.
So Listbox contains:
Apple
Orange
Fruit
i want to copy apple*.txt to destiondirectory, then copy orange*.txt to destination directory, and fruit*.txt to destinationdirectory.
After everything has been copied i want to create a text file of each thing being copied to it's own text file. So a directory listing from the destinationdirectory.
So i would just get a text file of all the files that match a specific criteria IE apple*
Thanks for the help and advice.
string[] filesToCopy = listBox1.Items.
string sourcefolder1 = #"K:\rkups";
string destinationfolder = #"K:\g_aa_ge\qc";
{
string source = Path.Combine(sourcefolder1, filesToCopy[] + ".ann");
string target = Path.Combine(destinationfolder, filesToCopy[] + ".ann");
File.Copy(source,target);
DirectoryInfo di = new DirectoryInfo(destinationfolder);
FileInfo[] annfiles = di.GetFiles(string+"*.txt);
foreach(FileInfo fi in annfiles)
the string+ is where i dont understand where/how to list each item in the listbox, and where
string[] filesToCopy = listBox1.Items. not sure how to list each item in the string
updated:
1) read each item in listbox
2) try to copy from a sourcedirectory to a destinationdirecory the item in listbox
3) repeat
thats it

I made a small example which is doing more or less what you wanted except generateing the log file.
You should be able to work it from there.
In my example, the code was just populating a second text box with the names of the copied files.
It was tested and compiled.
Hope this helps !
Anthony
private void button1_Click(object sender, EventArgs e)
{
string dirInput = "c:/test";
string dirOutput = "c:/test2";
listBox2.Items.Clear();
bool overwriteFilesInOutputDir = true;
if (Directory.Exists(dirInput))
{
if (!Directory.Exists(dirOutput))
Directory.CreateDirectory(dirOutput);
DirectoryInfo di = new DirectoryInfo(dirInput);
foreach (string filterItem in listBox1.Items)
{
FileInfo[] rgFiles = di.GetFiles(filterItem);
foreach (FileInfo fi in rgFiles)
{
File.Copy(fi.FullName, dirOutput + Path.DirectorySeparatorChar + fi.Name, overwriteFilesInOutputDir);
listBox2.Items.Add(fi.Name);
}
}
}
}
Like other people mentioned, it would help if you would try to do it yourself first and ask when you are stuck.
listBox1 contains the filters such as ".xls" or ".asp", listBox2 was just for me to check the names of the files copied.
Anthony

I'm still a little confused on what you want to do, but I fixed up your code for you...
string source, fileToCopy, target;
string sourcefolder1 = #"K:\rkups";
string destinationfolder = #"K:\g_aa_ge\qc";
DirectoryInfo di = new DirectoryInfo(destinationfolder);
FileInfo[] annfiles;
foreach (string s in listBox1.Items)
{
fileToCopy = s;
source = Path.Combine(sourcefolder1, fileToCopy + ".ann");
target = Path.Combine(destinationfolder, fileToCopy + ".ann");
File.Copy(source, target);
annFiles = di.GetFiles("*.txt");
// Do whatever you need to do here...
}

Related

Accessing files within child directories

I am trying to access the files in the images directory that lies within another directory but when I run my code it doesn't print out anything:
string path = #"C:\Path";
DirectoryInfo DFolder = new DirectoryInfo(path);
Collection cDetails = new Collection(DFolder);
string DFPath = DFolder.Name;
DirectoryInfo imDetails = new DirectoryInfo(imPath);
// Get Desired Directories
List<string> directoryFilter = new List<string> {"images", "videos", "RAW"};
List<DirectoryInfo> directoryList = DFolder
.GetDirectories("*", SearchOption.AllDirectories)
.Where(x => directoryFilter.Contains(x.Name.ToLower()))
.ToList();
string dpath = directoryList.ToString();
foreach (DirectoryInfo record in directoryList)
{
foreach (FileInfo file in record.GetFiles(#"*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(file); //It compiles but doesn't print anything on the console
}
}
Note: This isn't really an answer, so I'll delete it shortly, but wanted to give some sample code to test with in case it helps.
Your code works fine for me, so it seems that the problem is that either the directories don't exist, or they don't contain any files.
Here's a test program you can run which creates a bunch of directories under c:\temp, some of which have the names we care about. The names we care about are also found at different levels of depth in the path, yet they are all discovered:
static void CreateTestPathsAndFiles()
{
// Paths to create for testing. We will put a file in each directory below,
// but our search code should only print the file paths of those files that
// are directly contained in one of our specially-named folders
var testPaths = new List<string>
{
#"c:\temp\dummy1",
#"c:\temp\dummy1\raw", // This should print
#"c:\temp\dummy2",
#"c:\temp\dummy2\extra",
#"c:\temp\dummy3",
#"c:\temp\dummy3\dummy31",
#"c:\temp\dummy3\dummy32\raw", // This should print
#"c:\temp\extra",
#"c:\temp\images", // This should print
#"c:\temp\notUsed",
#"c:\temp\notUsed\videos", // This should print
#"c:\temp\raw", // This should print
#"c:\temp\videos\dummy1",
};
// Just something to make a unique file name
int fileId = 0;
// for testing, ensure that the directories exist and contain some files
foreach(var testPath in testPaths)
{
// Create the directory
Directory.CreateDirectory(testPath);
// Add a file to it
File.CreateText(Path.Combine(testPath, $"TempFile{fileId}.txt"))
.Write($"Dummy text in file {fileId}");
// Increment our file counter
fileId++;
}
}
static void Main(string[] args)
{
// Create our paths and files for testing
CreateTestPathsAndFiles();
// Now set our root directory, search for all folders matching our
// special folder names, and print out the files contained in them
var path = #"C:\Temp";
var directoryFilter = new List<string> {"images", "videos", "raw"};
// Get ALL sub-directories under 'path' whose name is in directoryFilter
var subDirectories = new DirectoryInfo(path)
.GetDirectories("*", SearchOption.AllDirectories)
.Where(x => directoryFilter.Contains(x.Name.ToLower()));
foreach (DirectoryInfo subDir in subDirectories)
{
foreach (FileInfo file in subDir.GetFiles(#"*", SearchOption.TopDirectoryOnly))
{
// We're using the FullName so we see the whole file path in the output
Console.WriteLine(file.FullName);
}
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
Note that the 5 files we expected to find are listed, but no others:
foreach (FileInfo file in record.GetFiles(#"*", SearchOption.TopDirectoryOnly))
{
Console.WriteLine(file); //It compiles but doesn't print anything on the console
}
SearchOption.TopDirectoryOnly will only search files in C://Path/images but not its subfolders.
a possible fix for this is to simply change your 2nd foreach loop to look like this:
foreach (FileInfo file in record.GetFiles(#"*", SearchOption.AllDirectories))
{
Console.WriteLine(file); //It compiles but doesn't print anything on the console
}
Edit:
Using SearchOption.AllDirectories as parameter is supposed to catch all cases of subfolders within your subfolder e.g. something like C://images//dir//somefile.txt instead of only taking the files within the topdirectory(in this case C://images). Which is(as i understood your question) exactly the kind of behaviour you were looking for.
Full code:
{
static void Main(string[] args)
{
// Directory Info
string path = #"C:\Path";
DirectoryInfo DFolder = new DirectoryInfo(path);
string DFPath = DFolder.Name;
// Get Desired Directories
List<string> directoryFilter = new List<string> { "images", "videos", "raw" };
List<DirectoryInfo> directoryList = DFolder.GetDirectories("*", SearchOption.AllDirectories).Where(x => directoryFilter.Contains(x.Name.ToLower())).ToList();
string dpath = directoryList.ToString();
foreach (DirectoryInfo record in directoryList)
{
foreach (FileInfo file in record.GetFiles(#"*", SearchOption.AllDirectories)) //searches directory record and its subdirectories
{
Console.WriteLine(file);
}
}
}
Final Edit: Sample output given the following structure:
C://Path//images//images.somefile.txt
C://Path//images//temp//images.temp.somefile.txt
C://Path//raw//raw.somefile.txt
C://Path//vidoes//videos.somefile.txt

How to list the search files into listbox by date modified using C#?

Here i have a problem with to list the search files into the listbox according to the date modified. The below code is shows only list the search files into the listbox. Could anyone help me how settle this problem please.....
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string search = TextBox1.Text; // here type the folder name
if (search != "")
//DirectoryInfo d = new DirectoryInfo(#"\\192.123.1.18\Report\Result" + search);
{
string[] files = Directory.GetFiles(#"\\192.123.1.16\Report\Result\"+ search, "*.txt", SearchOption.AllDirectories);
foreach (string file in files)
{
//ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file)); // listed all files in the search folder
}
{
search = "";
}
}
else
{
Response.Write("<script>alert('Please Enter Search Keyword');</script>");
}
}
For every file you can call: File.GetLastWriteTime and after that you sort this file list according to last write datetime.
Follow below article for more information.
https://msdn.microsoft.com/en-us/library/d5da1572.aspx
First create one class with name FileModifiedDate
Add to properties in this 1.Filename , 2.ModifiedDate and 3.File.
List<FileModifiedDate> FileList=new List<FileModifiedDate>();
foreach (string file in files)
{
//ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
// ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file)); //
FileModifiedDate FileInfo=new FileModifiedDate();
FileInfo.FileName=Path.GetFileName(file);
FileInfo.File=file;
FileInfo.ModifiedDate=File.GetLastWriteTime(path);
FileList.Add(FileInfo);
}
FileList=FileList.OrderByDescending(a=>a.ModifiedDate).ToList();
foreach (FileModifiedDate SingleFile in FileList)
{
//ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
ListBox1.Items.Add(new ListItem(SingleFile.FileName, SingleFile.file)); //
}
For every file you can call: FileInfo.LastWriteTimeUtc and after that, you should sort this file list according to their last write DateTime. DateTime class implements compasion operators so that you won't have trouble while sorting

In C# how can I get names of files from a checkListBox and move the files?

In C# I need to know how I can use item names in a checkListBox as file paths so a user can select the file names then click a button that will move those files to another file location on the pc. I already know how to get the files to appear in the checkListBox but I do not know how to detect file paths in the checkListBox so a user can move the selected files listed in the checkListBox.
If it helps, this is a better way of saying it. I want to get the listed files in a list box, and do something with them.
void sendbtn_Click(object sender, EventArgs e)
{
string destinationFolder = gamedir.Text;
string[] files = Directory.GetFiles(checkListView1.SelectedItems);
foreach(var file in files)
{
string destinationPath = Path.Combine(destinationFolder, file);
File.Copy(file.Fullname, destinationPath);
}
}
You can use System.IO.Directory
Directory List :
Directory.GetDirectories
File List under the directory
Directory.GetFiles("Path");
File full path :
System.IO.Path.GetFileName
Move File
Directory.Move
Create struct which contains file path and optionaly file name to shorten items in ComboBox:
struct ComboItem {
public string FileName { get; set; }
public string FilePath { get; set; }
public override string ToString() {
return FileName;
}
}
Overriding ToString() do the magic - in ComboBox you will see only file names. Populate ComboBox like this:
void FillCombo() {
var startPath = #"your path";
comboBox1.Items.Clear();
foreach (var file in Directory.GetFiles(startPath)) {
var item = new ComboItem {
FilePath = file,
FileName = Path.GetFileName(file)
};
comboBox1.Items.Add(item);
}
}
And than on move action get selected item:
var item = (ComboItem)comboBox1.SelectedItem;
In item you have file name and file path.

Find a file with particular substring in name

I have a dirctory like this "C:/Documents and Settings/Admin/Desktop/test/" that contain a lot of microsoft word office files. I have a textBox in my application and a button. The file's name are like this Date_Name_Number_Code.docx. User should enter one of this options, my purpose is to search user entry in whole file name and find and open the file.
thank you
string name = textBox2.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\");//Change path to yours
foreach (string file in allFiles)
{
if (file.Contains(name))
{
MessageBox.Show("Match Found : " + file);
}
}
G'day,
Here's the approach I used. You'll need to add a textbox (txtSearch) and a button (cmdGo) onto your form, then wire up the appropriate events. Then you can add this code:
private void cmdGo_Click(object Sender, EventArgs E)
{
// txtSearch.Text = "*.docx";
string[] sFiles = SearchForFiles(#"C:\Documents and Settings\Admin\Desktop\test", txtSearch.Text);
foreach (string sFile in sFiles)
{
Process.Start(sFile);
}
}
private static string[] SearchForFiles(string DirectoryPath, string Pattern)
{
return Directory.GetFiles(DirectoryPath, Pattern, SearchOption.AllDirectories);
}
This code will go off and search the root directory (you can set this as required) and all directories under this for any file that matches the search pattern, which is supplied from the textbox. You can change this pattern to be anything you like:
*.docx will find all files with the extention .docx
*foogle* will find all files that contain foogle
I hope this helps.
Cheers!
You can use Directory.GetFiles($path$).Where(file=>file.Name.Contains($user search string$).
Should work for you.
You can use the Directory.GetFiles(string, string) which searches for a pattern in a directory.
So, for your case, this would be something like:
string[] files =
Directory.GetFiles("C:/Documents and Settings/Admin/Desktop/test/",
"Date_Name_Number_Code.docx");
Then look through the files array for what you are looking for.
if you need info about the files instead of content:
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

C# comboBox, readall and working directory

What I have is a comboBox being populated from a code:
InitializeComponent();
DirectoryInfo dinfo = new DirectoryInfo(#"K:\ases");
FileInfo[] Files = dinfo.GetFiles("*.ssi", SearchOption.AllDirectories);
foreach (FileInfo file in Files)
{
comboBox1.Items.Add(file.Name);
}
Then i'm trying to ReadAllText from that selected item.
string contents = File.ReadAllText(comboBox1.Text);
When executed, it tries to read the file from the locale path, and of course the file isnt there. I also can't set the working directory because the comoboBox is populated from a huge range of subdirectories. How do I get the working directory of the item selected in the combobox WITHOUT expossing the whole directory path to the user?
Any help always welcomed
I thought i saw a few answers with someone suggesting private and hiding things in a combox box, where those suggestions taken down. is there a way to keep the full file info in the combobox and only display the file name?
There are several different ways to accomplish this, but the absolute easiest would be to store the directory path in an instance variable (we'll call it directoryPath) and use System.IO.Path.Combine() to reconstruct the path:
(some code eliminated for brevity)
public class Form1 : Form
{
private string directoryPath;
public Form1()
{
InitializeComponent();
DirectoryInfo dinfo = new DirectoryInfo(#"K:\ases");
FileInfo[] Files = dinfo.GetFiles("*.ssi", SearchOption.AllDirectories);
foreach (FileInfo file in Files)
{
comboBox1.Items.Add(file.Name);
}
directoryPath = dinfo.FullName;
}
private void YourFunction()
{
string contents = File.ReadAllText(System.IO.Path.Combine(directoryPath, comboBox1.Text);
}
}
You could also try adding the FileInfo to the ComboBox rather than the file's name and use SelectedItem rather than Text:
InitializeComponent();
DirectoryInfo dinfo = new DirectoryInfo(#"K:\ases");
comboBox1.DataSource = dinfo.GetFiles("*.ssi", SearchOption.AllDirectories);
comboBox1.DisplayMember = "Name";
Then you can do this to retrieve the file:
FileInfo file = (FileInfo)comboBox1.SelectedItem;
string contents = File.ReadAllText(file.FullName);
Instead of:
comboBox1.Items.Add(file.Name);
do:
comboBox1.Items.Add(file.FullName);
This will get you the full path to the file in order to read it.
See FileInfo for more details and other properties to use.
I think the best way for you is to use special class for items:
class FileInfoItem {
public FileInfoItem(FileInfo info) {
Info = info;
}
public FileInfo Info { get; set; }
public override string ToString() {
return Info.Name;
}
}
To add items in the combo box use the following code:
comboBox1.Items.Add(new FileInfoItem(file));
ComboBox will display the ToString() value of the items and also you can get the original FileInfo in the following maner:
((FileInfoItem)comboBox1.SelectedItem).Info;

Categories