Directory.GetFiles error - c#

my code
private void m1()
{
List<string> list = new List<string>();
foreach (string str in Directory.GetFiles("a1"))
{
if (Path.GetExtension(str).Contains("txt")) -- get all txt file in a1 folder
{
list.Add(Path.GetFileNameWithoutExtension(str));
}
}
base.SuspendLayout();
this.Combobox_1.Items.AddRange(list.ToArray());
base.ResumeLayout();
}
but combobox cannot list txt file in folder a1
Please helpme.

i think there is no need to store values first in a list and then add to a combobox.
it can be done directly to a combobox.
i have replace relative path a1 to a real one to let you understand easily.
foreach (string str in Directory.GetFiles(#"D:\"))
{
if (System.IO.Path.GetExtension(str).Contains("txt"))
{
this.Combobox_1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(str));
}
}

Related

Convert csv to double list with c#

with the following code Im trying to read a csv file that contains double values and convert it into a list. If I want to print that list The output just contains "system.collections.generic.list1 system.string". What is wrong in my code?
var filePath = #"C:\Users\amuenal\Desktop\Uni\test.csv";
var contents = File.ReadAllText(filePath).Split(';');
var csv = from line in contents
select line.Split(';').ToList();
foreach (var i in csv)
{
Console.WriteLine(i);
}
You got a couple things wrong with your code. First, you should most likely be using ReadAllLines() instead of ReadAllText(). Secondly, your LINQ query was returning a List<List<string>> which I imagine is not what you wanted. I would try something like this:
var filePath = #"C:\Users\amuenal\Desktop\Uni\test.csv";
//iterate through all the rows
foreach (var row in File.ReadAllLines(filePath))
{
//iterate through each column in each row
foreach(var col in row.Split(';'))
{
Console.WriteLine(col);
}
}
This should do good. Hope this helps.
var filePath = #"C:\Users\amuenal\Desktop\Uni\test.csv";
var contents = File.ReadAllLines(filePath);
var csv = (from line in contents
select line.Split(';')).SelectMany(x1 => x1);
foreach (var i in csv)
{
Console.WriteLine(i);
}
csv is an IEnumerable of a List of string. (in other words, each "i" is a list of string).
You need two loops:
foreach (var list in csv)
{
foreach(var str in list)
{
Console.WriteLine(str);
}
}

Inserting a text file into a hashtable with c#

i have a text file witch contains values like this :
0000000000
0000111222
0000144785
i need to insert this file into a HashTable with c#, this is what i've done so far :
string[] FileLines = File.ReadAllLines(#"D:TestHash.txt");
Hashtable hashtable = new Hashtable();
foreach (string line in FileLines)
{
// dont know what to do here
}
and after this i need to match a value from a textbox with the hashtable values. what should i do?
A Hashtable is a container for key-value-pairs. Since you only have values, not key-value-pairs, you don't need a hashtable, you need a HashSet:
HashSet<string> fileLineSet = new HashSet<string>(FileLines);
Check MSDN on how to use a hash set (including an example).
This reads all lines into a HashSet and checks the value of a TextBox against
HashSet<string> items = new HashSet<string>(File.ReadLines(#"D:\TestHash.txt"));
bool hasValue = items.Contains(TextBox.Text);
static void Main(string[] args)
{
string[] FileLines = File.ReadAllLines("your text file path");
Hashtable hashtable = new Hashtable();
foreach (string line in FileLines)
{
if (!hashtable.ContainsKey(line))
{
hashtable[line] = line;
}
}
foreach (var item in hashtable.Values)
{
//here you can match with your text box values...
//why you need to insert text file data into hash table really i dont know.from above foreach loop inside only you can match the values.might be you have some requirement for hash table i hope
string textboxVal = "text1";
if (item == textboxVal)
{
//both are matched.do your logic
}
else{
//not matched.
}
}
}

How to save from a listbox

I am attempting to save items from a listbox to a file; I have tried using things like
listbox.items
listbox.items.addrange
listbox.items.count
listbox.items.text (which doesn't give me an error but it also doesn't save)
Here is code:
private void button2_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, listBox1.Items.Count);
}
}
File.WriteAllText expects two items: a filepath, and the string to write (as a String):
You gave it:
ListBox.Items (a collection)
ListBox.Items.AddRange (a function)
ListBox.Items.Count (Valid, but not related to the actual items because it is just the count)
ListBox.Items.Text (what????) (this probably doesn't compile, as I'm not aware of that property)
You need to iterate through all the items, joining them all if you really want to use File.WriteAllText.
Something like:
File.WriteAllText(saveFileDialog1.FileName, String.Join(",", listBox1.Items));
//If the above doesn't do the cast implicitly, and its always better to be explicit!
File.WriteAllText(saveFileDialog1.FileName, String.Join(",", listBox1.Items.Cast<string>()));
String.Join
There are lots of other ways to generate the output of course, but the short of it is that you need to iterate each element in the Items collection and write it out to the file individually, or use a function like String.Join to do it all in one go.
You could loop through the items and create a string that contains all of them, then write that string to the file.
string itemString = "";
foreach (Item item in listbox1.Items)
{
itemString+=item.Text;
}
File.WriteAllText(saveFileDialog1.FileName, itemString);
You would probably want to add some sort of delimiter with each item, a comma, or a newline character or something so the file doesn't look like gibberish.
To save the items from listBox:
private void SaveItems()
{
using(StreamWriter sw = new StreamWriter("file.txt"))
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
sw.WriteLine(listBox1.Items[i]);
}
}
}
To load the items to listBox:
private void LoadItems()
{
using(StreamReader sr = new StreamReader("file.txt"))
{
while (!sr.EndOfStream)
{
listBox1.Items.Add(sr.ReadLine());
}
}
}
If you want to store every item in a ListBox into a file, it would be best to use File.WriteAllLines(String, String[]).
File.WriteAllLines(saveFileDialog1.FileName,
listBox1.Items.OfType<ListViewItem>().Select(i => i.Text).ToArray());

How to display folder name and all sub folder name in dropdownlist

I have code to find and display name of all folder in a rootfolder:
private string[] GetFolderNames(string virtualDirPath)
{
string[] Directories;
if (Directory.Exists(virtualDirPath))
{
Directories = Directory.GetDirectories(virtualDirPath);
for (int i = 0; i < Directories.Length; i++)
{
Directories[i] = MapUrl(Directories[i]);//map path to the folder
}
return Directories;
}
else
{
return null;
}
}
And code bind data to Dropdownlist:
string[] folders = GetFolderNames(RootPath);
if (folders != null)
{
dropDownListFolders.DataSource = folders;
dropDownListFolders.DataBind();
}
else
{
dropDownListFolders.Items.Insert(0, "No folders available..");
}
As the code above, the Dropdownlist display all the folder name in the Rootfolder with path= virtualDirPath;
But I wonder if in every child folder still has some subfolder, and in each subfolder has some more subfolder and so on more and more, so that how can I get all the name of that subfolders.
Try to make more for loop inside the first one, but it really mess me up. And it seems that is not the good way.
I need the Dropdownlist display all the subfolder name, child of sudfolder and child of child folder... in the rootfolder. Help! I need your opinion to find a better way to to it.
List<string> dirList = new List<string>();
DirectoryInfo[] dir = new DirectoryInfo(#"D:\Path").GetDirectories("*.*", SearchOption.AllDirectories);
foreach(DirectoryInfo d in dir)
{
dirList.Add(d.Name);
}
for (int i = 0; i < dirList.Count; i++)
{
Console.WriteLine(dirList[i]);
}
Try this, and get all the folder names in dirList and add it into the dropdown.
Its easier if you use the inbuild Directory.EnumerateDirectories method.
http://msdn.microsoft.com/de-de/library/vstudio/dd383462(v=vs.110).aspx
You just call it like this:
Directory.EnumerateDirectories("rootpath", "*", SearchOption.AllDirectories);
This will give you an IEnumerable of the all directories ("*") with its full path.
The enum SearchOption.AllDirectories is saying you want your search to be recursive.
The rootpath is your starting point.
Additional you could filter this method by extending the second paramater like this:
Directory.EnumerateDirectories("rootpath", "test*", SearchOption.AllDirectories);
This will result in a IEnumerable of all directories starting with test ("test*")
Edit:
You should consider displaying relative paths, instead of only names which can result in duplicate list entries.
var directories = (from x in Directory.EnumerateDirectories("rootpath", "*", SearchOption.AllDirectories)
select x.SubString("rootpath".Length)).ToList();
Use following method to get list of All the folders:
public void traverse(File file, List<String> dirList) {
// Print the name of the entry
System.out.println(file);
// Check if it is a directory
if (file.isDirectory()) {
System.out.println(file);
//add directory name in the list
dirList.add(file.getName());
// Get a list of all the entries in the directory
String entries[] = file.list();
// Ensure that the list is not null
if (entries != null) {
// Loop over all the entries
for (String entry : entries) {
// Recursive call to traverse
traverse(new File(file, entry),dirList);
}
}
}
}
once you get the list of directory and sub directories bind it with dropdown.
Use following code to call this method
DirectoryList directoryList = new DirectoryList();
//output pram
ArrayList<String> dirList = new ArrayList<String>();
directoryList.traverse(new File("D:\\Workspace\\Netbeans\\addapp"), dirList);

How to display form variables based on variable name

I have a list of variable names, lets say:
List<string> list = new List<string>();
list.Add("size");
list.Add("width");
list.Add("name");
list.Add("zip");
and i have text controls with those exact names, is there a way to loop through the list and only display what the value of the text control that i am asking for, like lets say something like this:
foreach (string txtctl in list)
{
Response.Write(Request.Form[txtctl]);
}
When i run this code the value just displays blank. Any suggestions?
string str = "";
foreach (string item in list)
{
TextBox txt = (TextBox)Form.FindControl(item);
if (txt != null)
{
str += item+":"+ txt.Text+"<br>";
}
}
Response.Write(str);

Categories