write the list of files in a folder to afile - c#

I wrote a code to read all the files in a folder, then write them to a file. All the code complies and runs okay, but the filenames of the files are not displayed in the new file.
Code:
private void Form1_Load(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog(); // Show the dialog.
// create a list to insert the data into
//put all the files in the root directory into array
string[] array1 = Directory.GetFiles(#"C:\Users\a3708906\Documents\Filereader m 15062012", "*.csv");
// Display all files.
TextWriter tw1 = new StreamWriter("C:/Users/a3708906/Documents/Filereader m 15062012/Filereader m 15062012/listoffiles.txt");
List<string> filenames = new List<string>();
tw1.WriteLine("--- Files: ---");
foreach (string name in array1)
{
tw1.WriteLine(name);
}
tw1.Close();
}
I would be grateful for your assistance.

You took the trouble to ask the user the folder location, yet you don't retrieve that folder location. The code should be
string[] array1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.csv");
// Display all files.
TextWriter tw1 = new StreamWriter(folderBrowserDialog1.SelectedPath+"/listoffiles.txt");

If the file isn't created (ie its just not there, even if it's just blank) then you problem lies with the stream writer. If this is the case I would suggest changing the direction of slashes so that your path is
TextWriter tw1 = new StreamWriter("C:\\Users\\a370890\\Documents\\Filereader m 15062012\\Filereader m 15062012\\listoffiles.txt");
If the file is created but nothing is written have a look at the flush command.
tw1.Flush();

Set a breakpoint to verify that GetFiles is returning files.
(Consider renaming array1 to something more meaningful)
Set a breakpoint on tw1.WriteLine(name) and ensure it is being hit.
It should be pretty easy to see the problem. My guess is that you simply aren't getting any files returned from GetFiles, but the breakpoints will tell you for sure. If your output file is created but missing the files - this is most likely the case.
If your output file doesn't exist; take a closer look at your file writing code.

I would say that your "space" in your folderpath is messing things up. Try to escape the "whitespace" by following the explanations in the msdn

I think problem is with your file path or file writing capability.
You use folderbrowserdialog but do not use it to get selected file
name. Instead you give path manually. also your output path can have
problem.

Try this :
using(system.IO.StreamWriter tw1 =
new system.IO.StreamWriter(#"C:/Users/a3708906/Documents/Filereader m 15062012/Filereader m 15062012/listoffiles.txt")
{
foreach (string name in array1)
{
tw1.WriteLine(name);
}
}

Related

C# System.IO.InvalidDataException zip file

System.IO.InvalidDataException: 'Number of entries expected in Central Directory Ending does not match the number of entries in the Central Directory.'
I'm getting this error on a code that i'm making "for fun" when i try to extract an zip file to a folder. Help ;-;
here's my situation: i made a Drag and Drop panel that recieve a file with a unique extension (the file is a zip but i changed the extension to test). Then the program will get the first line of text in the archive, and will create a folder to extract the files with the name given on that first line. But it gets that error on the extract code
string[] Arquivo = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (string arquivo in Arquivo)
{
MessageBox.Show(arquivo);
string[] allLines = File.ReadAllLines(arquivo);
string line = string.Empty;
if (allLines.Length >= 1)
{
line = allLines[0];
}
string Diretorio = #"C:\CommunicAlt\" + line;
MessageBox.Show(Diretorio);
if (!Directory.Exists(Diretorio))
{
Directory.CreateDirectory(Diretorio);
}
Path.ChangeExtension(arquivo, ".zip");
ZipFile.ExtractToDirectory(arquivo, Diretorio); //<--Here
I solved it, the problem is: the zip archive has a new line with a text to create a directory, but the visual studio can't extract it if the number of lines on the archive is different drom the default... so it won't extract.
The solution was to leave the zip archive untouched and create a new file with the config info.

C# not finding correct file path

I have a C# console application that sends Excel spreadsheet attachments through email.
I have given the file path in App.config. While trying to find the file, the code looks at proper location. But when trying to attach the file inside the foreach statement, it is looking in code's bin folder.
What am I doing wrong here?
DirectoryInfo dir1 = new DirectoryInfo(ConfigurationManager.AppSettings.Get("FilePath"));
FileInfo[] folderFiles = null;
folderFiles = dir1.GetFiles();
foreach (FileInfo aFile in folderFiles)
{
message.Attachments.Add(new Attachment(aFile.Name));
}
You need to use aFile.FullName (includes the full path) rather than aFile.Name (only the filename). If a command is not doing what you expect, you should check the documentation.
Alternatively, you could make it simpler:
string dir1 = ConfigurationManager.AppSettings.Get("FilePath");
foreach(string aFile in Directory.EnumerateFiles(dir1))
{
message.Attachments.Add(new Attachment(aFile));
}
as Directory.EnumerateFiles simply returns the full filenames and you would have to think about not doing so (e.g. by using Path.GetFileName) to do otherwise.

Mimic/Create Minimalist File Browser in C#

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)
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?
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);
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));
}

Outputting all text file titles to a textbox on Windows Form

Getting a bit stuck on a piece of code I'm trying to write and was hoping for a helping hand if anyone knows where I'm going wrong!
I have a simple Windows Form where I have a folder browser. The user will browse to a folder and any sub-folders within will then be searched for a text file that has the word "Passed" in the title (not the body of the text file itself). There will be files with "Passed" in from many different folders, and I want the functionality of the app to search through all sub-folders and return the all the files that have this in their name.
At present I have the following code:
private void searchButton_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please enter a path");
}
else
{
string[] allFiles = Directory.GetFiles(textBox1.Text, "*Passed*.*", SearchOption.AllDirectories);
string name = resultsText.Text;
foreach(string file in allFiles)
{
if (file.Contains("Passed"))
{
resultsText.Text = file;
}
}
}
}
However, in the resultsText texbox, it only returns 1 value. There are multiple files with "Passed" in their title and I would like to print them all to this textbox. Does anyone know where I may be going wrong and why I am only getting one file rather than all of them?
Also, this method seems to return the whole file path e.g.)
C:\Program Files\Test\abc\PassedTests.txt - does anyone know how I can trim the full path so it just returns the file name and extension?
Any help is greatly appreciated!
You need to append the text. At the moment, you're overwriting the previous value by using resultsText.Text = file;.
if (file.Contains("Passed"))
{
resultsText.AppendText(file);
}
What may be more performant would to use build your string using a StringBuilder and then assign that to the TextBox.
StringBuilder sb = new StringBuilder();
foreach(string file in allFiles)
{
if (file.Contains("Passed"))
{
sb.Append(file);
}
}
resultsText.Text = sb.ToString();
You have to change 1 line of code:
resultsText.Text = file;
To this:
resultsText.Text += file;
The + will append the text and not overwrite it.
this is the answer for your second question.
try this to get only the file name
Path.GetFileName(filepath)

Having Trouble Renaming Files that Match with my RegEx

I have an app that "cleans" "dirty" filenames. "Dirty" filenames have #%&~+{} in their filenames. What my app does is see if they are a match for a RegEx pattern i have defined and then send it to a method called FileCleanUp where it "cleans" the file and replaces invalid chars with a "". However, i noticed while i was running this, that my FileCleanup method only works on SOME files and not others!
Here is my code:
public class SanitizeFileNames
{
public void FileCleanup(List<string>paths)
{
string regPattern = (#"[~#&!%+{}]+");
string replacement = "";
Regex regExPattern = new Regex(regPattern);
foreach (string files2 in paths)
try
{
string filenameOnly = Path.GetFileName(files2);
string pathOnly = Path.GetDirectoryName(files2);
string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
string sanitized = Path.Combine(pathOnly, sanitizedFileName);
//write to streamwriter
System.IO.File.Move(files2, sanitized);
}
catch (Exception e)
{
//write to streamwriter
}
}
I tested on a few files with the names like: ~Test.txt, #Test.txt, +Text.txt, Test&Test.txt, T{e}st.txt, Test%.txt.
The ones i could not get to be renamed were: ~Test.txt, +Test.txt, T{e}st.txt
I debugged this and weirdly enough, it shows that these files that did not get renamed for some reason as correct on the debugger. Instead of showing ~Test.txt as a "sanitized" file name, it was Text.txt. So on the app side, it DOES read my foreach loop correctly.
However, i'm really stumped as to why it's not actually renaming these files. Anybody have a clue as to why this might be? Does it have to do with the File.Move() ?
EDIT: On further testing, i realize that it also doesn't rename files that are like this: ~~test.txt or ##test.txt
You have an empty catch block. Why don't you print out the exception message to see what's happening?
My guess is that the file names are matching the regex, but you're unable to rename the files because a file named Test.txt already exists after #Test.txt is renamed to that. Try renaming the other files to ~Test2.txt, +Test3.txt, T{e}st4.txt before running the program again.

Categories

Resources