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)
Related
The product I'm using is a Beijer HMI, currently i can generate a report and save it to a known location (my desktop - C:\Users\mrdav\Desktop).
I need to be able to search on my desktop for a file extension .xls and change its name.
When the report is generated by the HMI, it uses the date and time which means when the file is generated the name will be different every time.
On the press of a button i need to search my desktop for the .xls file and change its name to a variable.
// This is my variable with my program
string NewName = Globals.Tags.Tag1.Value;
The code that is generated needs to sit within the below example.
public partial class Screen1
{
void Button1_Click(System.Object sender, System.EventArgs e)
{
// Code to be added here...
}
}
Hopefully someone can help, I’m using windows compact framework so limited on functionality.
Any questions please let me know.
Thanks in advance,
Dave
Here is an example how you can do that:
DirectoryInfo dir = new DirectoryInfo(sExportPath);
FileInfo[] Files = dir.GetFiles("*.csv");
foreach(FileInfo file in Files )
{
// rename file
System.IO.File.Move(file.FullName, GenerateNewFileName());
}
//elsewhere in the class
private string GenerateNewFileName()
{
//here is where you implement creating or getting the filename that you want your file to be renamed to. An example might look like the below
string serialNumber = GetSerialNumber(); //Get the serial number that you talked about in the question. I've made it a string, but it could be an int (it should be a string)
return Path.ChangeExtension(serialNumber,".xls"); //to use path you will need a using statement at the top of your class file 'using System.IO'
}
This seems to work...but i know its not as tidy as it could be.
Any suggestions?
Thanks to all that helped, got there in the end!
void Button_Click(System.Object sender, System.EventArgs e)
{
try
{
// Location for new file
string NewFileName = #"c:\users\mrdav\desktop\testfolder\";
// Add varibale name to new file
NewFileName += Globals.Tags.Tag1.Value;
// add .xls extention to new file
NewFileName += ".xls";
//show new file name to check all ok
MessageBox.Show (NewFileName);
//search for .xls in known directory
DirectoryInfo di = new DirectoryInfo(#"c:\users\mrdav\desktop");
FileInfo[] Files = di.GetFiles("*.xls");
// if files exist with .xls extention
foreach(FileInfo file in Files )
{
// show full file name
MessageBox.Show (file.FullName);
//rename old file to new file name and move to new folder
File.Move(file.FullName, NewFileName);
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
Im making a mp3 player in c# and im using a autoload function and it works perfectly to load and play, but the "problem" in in the list box where the .mp3 files are displayed. it shows the file directory and file extension like this:
C:\Users\Felix\Documents\songs_here\list_1\Admiral P - Engle.mp3
and insteed of that i would like it to show:
Admiral P - Engel
is this possible and how to i do it? the file load code is:
private void PopulateListBox1(string folder)
{
string[] files = Directory.GetFiles(folder);
foreach (string file in files)
listBox1.Items.Add(file);
}
PopulateListBox1(dir1);
Thanks in advance!!
You can use Path.GetFileNameWithoutExtension.
Path.GetFileNameWithoutExtension Method (String)
Returns the file name of the specified path string without the extension.
For example:
Path.GetFileNameWithoutExtension("C:\Users\...\songs_here\list_1\Admiral P - Engle.mp3");
Would return:
Admiral P - Engle
Update:
I'm assuming from your comment that you want to display the file name but still have a reference to the path to the file to pass to your player.
You'll need to create your own class to hold the mp3 file name and path like this:
public class MusicFile
{
public string Path;
public string FileName;
public override string ToString()
{
return FileName;
}
}
private void PopulateListBox1(string folder)
{
string[] files = Directory.GetFiles(folder);
foreach (string file in files)
{
var music = new MusicFile
{
Path = file,
FileName = Path.GetFileNameWithoutExtension(file)
};
listBox1.Items.Add(music);
}
}
This shows how to loop through each item and get the path, but you could also use events such as SelectedIndexChanged depending on your needs.
foreach (var item in listBox1.Items)
{
var filepath = ((MusicFile)item).Path; // Shows the full path, pass this to the player
}
Using Linq one line code
private void PopulateListBox1(string folder)
{
listBox1.DataSource =Directory.GetFiles(folder).Select(x => Path.GetFileNameWithoutExtension(x)).ToList();
}
as the file naming pattern is the same, first you might want to check file extension with a string split on dot character on every file entry, then for each file if it is mp3 extension , split an pop the last word
I am creating application. In that, I put combo box, combo box filled by application no. came from db. on the selection of combo box the grid fill that files which in another machine in drive. Like //user/public/af001/edit/test.JPEG and in grid I put the download link on particular row for download that file in my machine but issue is when I am downloading that file, I am not geting //user/public/af001/edit/test.JPEG.
if (e.Column Index == 0)
{
int row;
//Get the row index
row = e.Row Index;
string old Path = #"~\\Users\Public\AS\AFS1402190001\Edit\test.JPEG";
string new path = #"E:\example\";
string new File Name = "new file name";
File Info f1 = new File Info(old Path);
if (f1.Exists)
{
if (!Directory.Exists(new path))
{
Directory.Create Directory(new path);
}
f1.Copy To(string.Format("{0}{1}{2}", new path, new File Name, f1.Extension));
}
}
Can you tell me what is the issue?
Thanks for help.
The problem is at this line:
string.Format("{0}{1}{2}", new path, new File Name, f1.Extension);
it looks you are not building a correct file patch. try to use System.IO.Path.Combine to combine directory and fileName. something like:
System.IO.Path.Combine(dirPath, string.Format("{0}.{1}", fileName, extension));
of course, you might want to make sure the path/filename does not have invalid chars, you can use System.IO.Path.GetInvalidFileNameChars() and System.IO.Path.GetInvalidPathChars() to get those illegal chars that you need to avoid.
i want to create C# mass file renamer, here is my UI
i have created tes folder, inside of tes there's a file which is 1.txt.
i want to create my program to add prefix and suffix to the files, so 1.txt will become
prefix1suffix
but then i got an error
it's said file already exist though there's only one file on tes folder, which is 1.txt how do i make it work ? where's the error comes from ?
i have tried the following code
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
File.Move(f.FullName,"stackoverflow");
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
and it returns same error as the second picture above.
the following picture is tes folder, there's nothing in tes folder except 1.txt
You are calling File.Move() with a full path for your sourceFileName and a relative path for your destFileName. The relative file path is relative to the current working directory and not to the source file path. I expect that a stackoverflow file exists in the current working directory, most likely created the first time you ran this code.
your File.Move is changing them all to StackOverflow not using the prefix and suffix. If you only have one file in the directory it shouldn't be an issue. Are you sure there is only 1 file?
public static void Move(
string sourceFileName,
string destFileName
)
Looking at this answer might be the clue as you are specifying relative path for the destination file. To obtain the current working directory, see GetCurrentDirectory
The sourceFileName and destFileName arguments are permitted to specify
relative or absolute path information. Relative path information is
interpreted as relative to the current working directory.
You should change
File.Move(f.FullName,"stackoverflow");
to
string fileName = f.Name.Replace(f.Extenstion,string.Empty);
string newFileName = string.Format("{0}{1}{2}",prefix,fileName,suffix);
string newFileWithPath = Path.Combine(f.Directory,newFileName);
if (!File.Exists(newFileWithPath))
{
File.Move(f.FullName,newFileWithPath);
}
The code above will give you that error since, after the first run through, "stackoverflow" exists as a file. Make sure that you check if the destination file exists (using File.Exists) before calling File.Move.
Since your goal is renaming, I would suggest using a test folder filled with files rather than using a piecemeal approach. See if something like this helps:
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
f.MoveTo(#filepath + #"\" + prefix + f.Name.Insert(f.Name.LastIndexOf('.'),suffix));
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
on a side note using a listview to display the filenames and the changes before they're committed will help prevent unwanted changes.
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);
}
}