I tried the following using C#:
using System.IO;
string[] FileName = Directory.GetFiles("dir");
for (int i = 0; i < dir.Length; i++)
{
comboBox1.Items.Add(Dirs[i]);
}
But for some reason it only gets 5 files from this folder. Is it possible to get all of the file's names and put them in the combobox?
Thanks in advance.
Problem : You are getting all the FileNames into FileName string array but you are only getting 5 because you are not using FileName string array in your code.
Solution : You need to use FileName String Array instead of dir.
Try This:
string[] FileName = Directory.GetFiles("dir");
for (int i = 0; i < FileName.Length; i++)
{
comboBox1.Items.Add(FileName[i]);
}
OR
string [] FileNames = Directory.GetFiles("dir");
foreach (var filename in FileName)
{
comboBox1.Items.Add(filename);
}
Probably you are looking for this:
string[] FileName = Directory.GetFiles("dir","*",SearchOption.AllDirectories);
foreach(string fileName in Directory.GetFiles("dir", "*", SearchOption.AllDirectories))
{
comboBox1.Items.Add(fileName));
}
Related
I have many files of data in txt files like this short example
123456
754124
956412
789654
They can have tens of lines in each file. Each file populates a separate combobox. From a static file in a folder I can make it work
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
for (int i = 0; i < fname.Length; i++)
{
string[] lineOfContents = File.ReadAllLines(#"d:\\temp\\" + fname[i] + ".txt");
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
foreach (var line in lineOfContents)
{
string[] data = line.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
cmbobox.Items.Add(data[0]);
}
cmbobox.SelectedIndex = 0;
}
but I need to do this when I read the data from embedded resources. I pulled the text files into the project.properties.resources so I have them inside the exe. I understand I will need to stream it out from resources but then I get lost in knowing how to convert the stream with all its newlines etc and format it to add it to the combobox.
I tried many things and the closest I think I have got is as follows although it tells me I have hold of nothing (NULL).
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
var assembly = Assembly.GetExecutingAssembly();
for (int i = 0; i < fname.Length; i++)
{
string lineOfContents;
string name = fname[i] + ".txt";
using (Stream resourceStream = assembly.GetManifestResourceStream(name))
{
if (resourceStream != null)
{
using (StreamReader reader = new StreamReader(resourceStream))
{
lineOfContents = reader.ReadToEnd();
}
}
}
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
cmbobox.SelectedIndex = 0;
}
Any help in getting the stream into the combo box would be much appreciated.
Thanks for the link below, I did not get that when I searched so thanks and it helped. The working code before I tidy it up is:
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
for (int i = 0; i < fname.Length; i++)
{
string resource_data = Properties.Resources.ResourceManager.GetString(fname[i]);
string[] lineOfContents = resource_data.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
foreach (var line in lineOfContents)
{
string[] data = line.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
cmbobox.Items.Add(data[0]);
}
cmbobox.SelectedIndex = 0;
}
Thanks for the links, I did not get that when I searched so thanks and it helped. The working code before I tidy it up is:
string[] fname = {"fridge", "washer", "freezer", "dishwasher"};
for (int i = 0; i < fname.Length; i++)
{
string resource_data = Properties.Resources.ResourceManager.GetString(fname[i]);
string[] lineOfContents = resource_data.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
ComboBox cmbobox = (ComboBox)this.Controls["cmbobx_" + fname[i]];
foreach (var line in lineOfContents)
{
string[] data = line.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
cmbobox.Items.Add(data[0]);
}
cmbobox.SelectedIndex = 0;
}
I't trying to get my program to read the most recent file in a directory with a few similar files and retrieve a name but its still reading all the files. If anyone knows why I'd appreciate the help :)
EDIT: Undo
here's my code:
public GetMyNames()
{
DirectoryInfo fileDirectory = new DirectoryInfo(#"C:\user\mark\folder");
List<string> files = new List<string>();
int creationDate = 0;
string CreationDate = "";
foreach (FileInfo fileInfo in fileDirectory.GetFiles("*.txt"))
{
string creationTime = fileInfo.CreationTime.ToString();
string[] bits = creationTime.Split('/', ':', ' ');
string i = bits[0] + bits[1] + bits[2];
int e = Int32.Parse(i);
if (e > creationDate)
{
creationDate = e;
files.Add(fileInfo.Name);
}
}
foreach(string file in files)
{
string filePath = fileDirectory + file;
string lines = ReadAllLines(filePath);
foreach (string line in Lines)
{
Name = Array.Find(dexLines,
element => element.StartsWith("Name", StringComparison.Ordinal));
}
MyName = Name[0];
}
Note that OrderBy runs at an order of O(nlog(n)) as it sorts the enumerable.
I suggest using Linq Max extension method, that is:
newestFile = files.Max(x => x.CreationDate);
this is more efficient (runs at an order of O(n)) and is more readable in my opinion
Why not use Linq and order by the date?
files.OrderBy(x => x.CreationDate)
[code="C#"]
int counter=0;
string filename = "Folio-Mapping-Form-" + myinvestorid.Value +".pdf";
counter++;
for (int i = 0; i <=counter; i++)
{
appendfile +=filename;
htmlToPdfConverter.ConvertHtmlToFile(htmlString, baseUrl,
filePath + filename);
}
here I having string filename which is having many filename but I want to store filename into array.how can I store filename into array
I don't quite understand your question .Could you paste more code?Based on what I understand,try to use string[] or use List<string> then call ToArray method.
I have created something that grabs all file names that have the extension .lua with them. This will then list them in a CheckListBox. Everything goes well there but I want to know which one of the CheckListBox's are ticked/checked and then open them in notepad.exe.
To dynamically add the files Code (works perfectly, and adds the files i want)
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appData + "\\Lua";
string[] fileArray = Directory.GetFiles(path, "*.lua");
for (int i = 0; i < fileArray.Length; i++)
{
string Name = Path.GetFileName(fileArray[i]);
string PathToLua = fileArray[i];
ScriptsBoxBox.Items.AddRange(Name.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
Console.WriteLine(fileArray[i]);
}
Then when i check the items i want to open in notepad i use `
System.Diagnostics.Process.Start("notepad.exe", ScriptsBoxBox.CheckedItems.ToString());
Or
System.Diagnostics.Process.Start("notepad.exe", ScriptsBoxBox.CheckedItems);
Neither works and im pretty sure it's on my end. So my problem is that i cannot open the file that is ticked/checked in checklistbox and want to resolve this problem. However when I do
System.Diagnostics.Process.Start("notepad.exe", PathToLua);
It opens the files with .lua extension ticked or not which makes sense.
I don't think there are any arguments that you can pass to notepad to open a list of specific files. However, you can use a loop to open each file.
foreach (var file in ScriptsBoxBox.CheckedItems)
{
System.Diagnostics.Process.Start("notepad.exe", file);
}
I don't know WinForms as well as WPF but here goes
You need an object that contains your values
public class LuaFile
{
public string FileName { get; set; }
public string FilePath { get; set; }
public LuaFile(string name, string path)
{
FileName = name;
FilePath = path;
}
public override string ToString()
{
return FileName;
}
}
Replace your for loop with
foreach (var file in files)
{
ScriptsBoxBox.Items.Add(new LuaFile(Path.GetFileName(file), file));
}
And to run the checked files
foreach (var file in ScriptsBoxBox.CheckedItems)
{
System.Diagnostics.Process.Start("notepad.exe", ((LuaFile)file).FilePath);
}
Thanks everyone that helped but I solved it on my own (pretty easy when you read :P)
For anyone in the future that wants to do this here is how i accomplished it.
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appData + "\\Lua";
string[] fileArray = Directory.GetFiles(path, "*.lua");
for (int i = 0; i < fileArray.Length; i++)
{
string Name = Path.GetFileName(fileArray[i]);
string PathToLua = fileArray[i];
//ScriptsBoxBox.Items.AddRange(Name.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
// Console.WriteLine();
Console.WriteLine(ScriptsBoxBox.CheckedItems.Contains(Name));
var pathname = ScriptsBoxBox.CheckedItems.Contains(Name);
if (ScriptsBoxBox.CheckedItems.Contains(Name))
{
System.Diagnostics.Process.Start("notepad.exe", fileArray[ScriptsBoxBox.CheckedItems.IndexOf(Name)]); // I supposed this would get the correct name index, and it did! fileArray by default seems to get the path of the file.
}
When I use the line of code as below , I get an string array containing the entire path of the individual files .
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf");
I would like to know if there is a way to only retrieve the file names in the strings rather than the entire paths.
You can use Path.GetFileName to get the filename from the full path
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
.Select(Path.GetFileName)
.ToArray();
EDIT: the solution above uses LINQ, so it requires .NET 3.5 at least. Here's a solution that works on earlier versions:
private string[] pdfFiles = GetFileNames("C:\\Documents", "*.pdf");
private static string[] GetFileNames(string path, string filter)
{
string[] files = Directory.GetFiles(path, filter);
for(int i = 0; i < files.Length; i++)
files[i] = Path.GetFileName(files[i]);
return files;
}
You can use the method Path.GetFileName(yourFileName); (MSDN) to just get the name of the file.
You could use the DirectoryInfo and FileInfo classes.
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");
//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;
string[] fileEntries = Directory.GetFiles(directoryPath);
foreach (var file_name in fileEntries){
string fileName = file_name.Substring(directoryPath.Length + 1);
Console.WriteLine(fileName);
}
There are so many ways :)
1st Way:
string[] folders = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
string jsonString = JsonConvert.SerializeObject(folders);
2nd Way:
string[] folders = new DirectoryInfo(yourPath).GetDirectories().Select(d => d.Name).ToArray();
3rd Way:
string[] folders =
new DirectoryInfo(yourPath).GetDirectories().Select(delegate(DirectoryInfo di)
{
return di.Name;
}).ToArray();
You can simply use linq
Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));
Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetNameOfFiles
{
public class Program
{
static void Main(string[] args)
{
string[] fileArray = Directory.GetFiles(#"YOUR PATH");
for (int i = 0; i < fileArray.Length; i++)
{
Console.WriteLine(fileArray[i]);
}
Console.ReadLine();
}
}
}