Question

I'm trying to make a program that stores files as *.txt based documents. I want to be able to click a button and pull up a list of currently stored files

(Located in C:\ProgramData\ProgramName\Incidents)

enter image description here

Above is an example of what I'm trying to accomplish where 140219-000727 is the name of the file, the rest isn't need. Clicking Open or Double Clicking would "Open" that file and parse the .txt into pre-existing forms on a WinForm application that I have already created.

What is the best way to go about doing this with a minimal hit on system resources?

Was it helpful?

Solution

I think Directory.GetFiles is what you are looking for. You can use the simplest mask "*.txt" to fetch all txt files and then using Path.GetFileName cut the file name from the full path. And later (on double click or button click) use the directory name + file name for opening:

//populating:
var files = Directory.GetFiles(YOUR_FOLDER_PATH, "*.txt");
foreach (var file in files)
{
    var fileName = Path.GetFileName(file);
    //assuming ListBox:
    listBox.Items.Add(filename);
}

//opening (from listbox)
var fileName = Path.Combine(YOUR_FOLDER_PATH, listBox.SelectedItem.ToString());
File.ReadAllText(fileName);

OTHER TIPS

You just need a FolderBrowserDialog control.

var fileNames = new List<string>();
var fileContents = new Dictionary<string, string>();
var filePaths = Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.txt");
foreach (var filePath in filePaths)
{
    var fileName =new FileInfo(filePath).Name; 
    fileNames.Add(fileName);
    fileContents.Add(fileName, File.ReadAllText(filePath));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top