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);
Related
This question might have been asked before, however I am not able to pass three parameters in single loop which I need for my method. I have like thousands of files in that directory (xml,jpg,tiff) (mixed).
This is something what I'm trying to get.
protected void btn_Click(object sender, EventArgs e)
{
var path = #"d:\xmlfiles";
foreach (var file in Directory.GetFiles(path))
{
ProcessFile(file,param2,param3);
}
}
static void ProcessFile(string file_xml, string file_jpg, string file_tiff)
{
// do processing here...
//Adding data to sql
}
I tried Path.GetExtension, but it only gives extension. I have to pass file name and the logic is in the method Processfile().
I saw many questions asked before which only returns single file.
Any other way for a workaround?
Directory.GetFiles() method in C#
Directory.getfiles(): specific names of files c#
Multiple filters with Directory.GetFiles?
Directory.GetFiles() pattern match in C#
Any helpe would be appreciated. Thanks.
So you have a directory containing files like this:
Foo.xml, Foo.jpg, Foo.tiff
Bar.xml, Bar.jpg, Bar.tiff
Baz.xml, Baz.jpg, Baz.tiff
And you want to process equally named files together. Then why not pick and enumerate one extension, and reconstruct the accompanying file names:
foreach (var xmlFile in Directory.GetFiles(path, "*.xml"))
{
var extensionLess = Path.GetFilenameWithoutExtension(xmlFile);
var jpgFile = Path.Combine(path, extensionLess + ".jpg");
var tiffFile = Path.Combine(path, extensionLess + ".tiff");
ProcessFile(xmlFile, jpgFile, tiffFile);
}
I am trying to check to see if the file exists if it doesn't leave the textbox blank! it doesn't work
string[] filePaths = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*");
if (!File.Exists(filePaths.ToString()))
{
TboxLeftTable.Text = "";
}
else
{
TboxLeftTable.Text = System.IO.Path.GetFileName(filePaths[0]);
}
Well, one problem you have is that you are just trying to use ToString() on an array. Since Directory.GetFiles() returns an array of file names, you need to iterate over those files and check them one at a time. Something like this:
string[] filePaths = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*");
foreach (string curFilePath in filePaths)
{
if (!File.Exists(curFilePath))
{
TboxLeftTable.Text = "";
}
else
{
TboxLeftTable.Text = System.IO.Path.GetFileName(curFilePath);
}
}
Once your code is fixed you still have weird logic. If we take your logic and spell it out in a sentence it reads like this:
Get a list of files from a folder, then immediately check to see if the file(s) in that folder exist
I think what you want to do instead is:
Get a list of files from a folder, if one exists display the very first one's name in a textbox, if it does not, display nothing
If I am right, then your code would look like this:
// Gets all string file paths in a folder
// then grabs the first one, or null if there are none
string filePath = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*").FirstOrDefault();
// if the path is not null, empty or whitespace
if(!string.IsNullOrWhiteSpace(filePath)
{
// then get the filename and put it in the textbox
TboxLeftTable.Text = Path.GetFileName(filePath);
}
else
{
// There were no files in the folder so make the textbox empty
TboxLeftTable.Text = string.Empty;
}
This is the working code. Thanks for the help!
string[] filePaths = Directory.GetFiles(#"C:\TwinTable\LeftTableO0201", "*.*");
if (filePaths.Length > 0)
TboxLeftTable.Text = System.IO.Path.GetFileName(filePaths[0]);
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...
}
I need some help in renaming some images in a directory located at /images/graphicsLib/.
All image names in /graphicsLib/ have naming convention that looks like this:
400-60947.jpg. We call the "400" part of the file the prefix and we call the "60957" part the suffix. The entire file name we call the sku.
So if you saw the contents of /graphicLib/ it would look like:
400-60957.jpg
400-60960.jpg
400-60967.jpg
400-60968.jpg
402-60988.jpg
402-60700.jpg
500-60725.jpg
500-60733.jpg
etc...
Using C# & System.IO , what is an acceptable way to rename all image files base on the prefix of the file name? Users need to be able to enter in the current prefix, see all images in the /graphicsLib/ that match, then enter in the new prefix to have all those files renamed with the new prefix. Only the prefix of the file gets renamed, the rest of the file name needs to be unchanged.
What I have so far is:
//enter in current prefix to see what images will be affected by
// the rename process,
// bind results to a bulleted list.
// Also there is a textbox called oldSkuTextBox and button
// called searchButton in .aspx
private void searchButton_Click(object sender, EventArgs e)
{
string skuPrefix = oldSkuTextBox.Text;
string pathToFiles = "e:\\sites\\oursite\\siteroot\\images\graphicsLib\\";
string searchPattern = skuPrefix + "*";
skuBulletedList.DataSource = Directory.GetFiles(pathToFiles, searchPattern);
skuBulletedList.DataBind();
}
//enter in new prefix for the file rename
//there is a textbox called newSkuTextBox and
//button called newSkuButton in .aspx
private void newSkuButton_Click(object sender, EventArgs e)
{
//Should I loop through the Items in my List,
// or loop through the files found in the /graphicsLib/ directory?
//assuming a loop through the list:
foreach(ListItem imageFile in skuBulletedList.Items)
{
string newPrefix = newSkuTextBox.Text;
//need to do a string split here?
//Then concatenate the new prefix with the split
//of the string that will remain changed?
}
}
You could look at string.Split.
Loop over all files in your directory.
string[] fileParts = oldFileName.Split('-');
This will give you an array of two strings:
fileParts[0] -> "400"
fileParts[1] -> "60957.jpg"
using the first name in your list.
Your new filename then becomes:
if (fileParts[0].Equals(oldPrefix))
{
newFileName = string.Format("(0)-(1)", newPrefix, fileParts[1]);
}
Then to rename the file:
File.Move(oldFileName, newFileName);
To loop over the files in the directory:
foreach (string oldFileName in Directory.GetFiles(pathToFiles, searchPattern))
{
// Rename logic
}
Actually you should iterate each of the files in the directory and rename one by one
To determine the new file name, you may use something like:
String newFileName = Regex.Replace("400-60957.jpg", #"^(\d)+\-(\d)+", x=> "NewPrefix" + "-" + x.Groups[2].Value);
To rename the file, you may use something like:
File.Move(oldFileName, newFileName);
If you are not familiar with regular expressions, you should check:
http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx
And download this software to pratice:
http://www.radsoftware.com.au/regexdesigner/
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;