C# comboBox, readall and working directory - c#

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;

Related

Convert files following the order of a list C#

I need to convert images(like .jpg) to PDF files for an assignment for school. I have a ListBox where I put the pages of the PDF file, so the user can reorder the list and convert the files in that order.
I have the files in a temporary folder in order to get the files there to convert them to PDF.
My problem here is : how do I convert the files with the order that the user had chosen?
I already searched and I tried to do a Class with the strings ID and Name so i get the ID from the item in the ListBox and change it on a new list. And i think after, I do a foreach() loop where I get the files from the temporary folder and merge them in a new PDF file, but to do in the order I want, I think I have to compare the name of the file with the name in the list and, if it matches, convert and add it, if not, pass to the next file.
But I don't know how to do it.
Can please someone help me getting this right?
Thanks in advance!
I'm sending my code to:
//the open files button
private void proc2_Click(object sender, EventArgs e)
{
OpenFileDialog dialogo = new OpenFileDialog();
dialogo.Title = "Search files";
dialogo.InitialDirectory = #"E:\";
dialogo.Filter = "Images (.bmp,.jpg,.png,.tiff,.tif) |*.bmp;*.jpg;*.png;*tiff;*tif|All of the files (*.*)|*.*";
DialogResult resposta = dialogo.ShowDialog();
if (resposta == DialogResult.OK)
{
string caminhoCompleto = dialogo.FileName;
caminho2 = dialogo.SafeFileName;
caminhotb2.Text = caminhoCompleto;
string fish = "";
string path = #"C:\temporario";
if(Directory.Exists(path))
{
fish=Path.Combine(path, caminho2);
}
else
{
Directory.CreateDirectory(path);
fish = Path.Combine(path, caminho2);
}
File.Create(fish);
listaimg.Items.Add(caminho2);
}
}
public string[] GetFilesImg4() //jpg files
{
if (!Directory.Exists(#"C:\temporario"))
{
Directory.CreateDirectory(#"C:\temporario");
}
DirectoryInfo dirInfo = new DirectoryInfo(#"C:\temporario");
FileInfo[] fileInfos4 = dirInfo.GetFiles("*.jpg");
foreach (FileInfo info in fileInfos4)
{
if (info.Name.IndexOf("protected") == -1)
list4.Add(info.FullName);
}
return (string[])list4.ToArray(typeof(string));
}
If both actions happen in the same process, you can just store the list of file names in memory (and you already do add them to listaimg):
public string[] GetFilesImg4() //jpg files
{
string tempPath = #"C:\temporario";
if (!Directory.Exists(tempPath))
{
foreach (string filename in listimga.Items)
{
if (!filename.Contains("protected"))
list4.Add(Path.Combine(tempPath, filename);
}
}
return (string[])list4.ToArray(typeof(string));
}
if these are different processes then you can just dump content of your listimga at some point and then read it from the same file. In the example below I store it to file named "order.txt" in the same directory, but logic may be more complicated, such as merging several files with a timestamp and such.
// somewhere in after selecting all files
File.WriteAllLines(#"c:\temporario\order.txt", listimga.Items.Select(t=>t.ToString()));
public string[] GetFilesImg4() //jpg files
{
string tempPath = #"C:\temporario";
if (!Directory.Exists(tempPath))
{
var orderedFilenames = File.ReadAllLines(Path.Combine(tempPath, "order.txt")); // list of files loaded in order
foreach (string filename in orderedFilenames)
{
if (!filename.Contains("protected"))
list4.Add(Path.Combine(tempPath, filename);
}
}
return (string[])list4.ToArray(typeof(string));
}
it's also a good idea to examine available method on a class, such as in this case string.IndexOf(s) == -1 is equivalent to !string.Contains(s) and the latter is much more readable at least for an English speaking person.
I also noticed that your users have to select documents one by one, but FileOpen dialogs allow to select multiple files at a time, and I believe it preserves the order of selection as well.
If order of selection is important and file open dialogs don't preserve order or users find it hard to follow you can still use multiple file selection open dialog and then allow to reorder your listimga list box to get the order right.

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.

Can't add files to listbox...READ

I'm using a code to show all startup items in listbox with environment variable "%appdata%
There is some errors in this code that I need help with....
Check code for commented errors
Is there any other solution but still using %appdata%?
This is the code:
private void readfiles()
{
String startfolder = Environment.ExpandEnvironmentVariables("%appdata%") + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
foldertoread(startfolder);
}
private void foldertoread(string folderName)
{
FileInfo[] Files = folderName.GetFiles("*.txt"); // HERE is one error "Getfiles"
foreach (var file in Directory.GetFiles(folderName))
{
startupinfo.Items.Add(file.Name); // here is another error "Name"
}
}
This line won't work because folderName is a string (and does not have a GetFiles method):
FileInfo[] Files = folderName.GetFiles("*.txt");
The second error is occurring because the file variable is a string containing the filename. You don't need to call file.Name, just try the following:
startupinfo.Items.Add(file);
I don't think you need the following line:
FileInfo[] Files = folderName.GetFiles("*.txt");
The foreach loop will generate what you need.
Secondly, the file variable is a string, so rather than calling:
startupinfo.Items.Add(file.Name);
...call instead:
startupinfo.Items.Add(file);
Finally, instead of a var type for your loop, you can use a string, and you can specify the file type filter:
foreach (string fileName in Directory.GetFiles(folderName, "*.txt"))
The string object doesn't have a GetFiles() method. Try this:
string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
string[] files = Directory.GetFiles(startfolder, "*.txt");
foreach (string file in files)
{
startupinfo.Items.Add(Path.GetFileNameWithoutExtension(file));
}
Path.GetFileNameWithoutExtension(file) returns just the file name instead of full 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# listbox to file listing

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...
}

Categories