I'm trying to make a C# music player and to do so, I'm using the WMP object found in win forms, I got it to load files from an specific folder on the press of a button, however, I want it to load every media file (FLAC, mp3, wav...) in an specific folder and its sub folders.
by now the code I have to load files is as follows.
string[] path, files; //Global Variables to get the path and the file name
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//This function displays the files in the path and helps selecting an index
axWindowsMediaPlayer1.URL = path[listBox1.SelectedIndex];
axWindowsMediaPlayer1.uiMode = "None";
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if(ofd.ShowDialog() == DialogResult.OK)
{
//Function that loads the files into the list.
files = ofd.SafeFileNames;
path = ofd.FileNames;
for (int i = 0; i < files.Length; i++)
{
listBox1.Items.Add(files[i]);
}
}
}
Step 1: Use FolderBrowserDialog instead of OpenFileDialog, this helps you to select a folder instead of a file
Step 2: After selecting a file, You can use the method Directory.EnumerateFiles(Your_Path, ".", SearchOption.AllDirectories) to get all files in the selected folder.
Try this:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = listBox1.Items[listBox1.SelectedIndex];
axWindowsMediaPlayer1.uiMode = "None";
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog() == DialogResult.OK)
{
LoadFiles(FBD.SelectedPath, new string[] { ".mp3", ".wav" }); //You can add more file extensions...
}
}
private void LoadFiles(string FolderPath, string[] FileExtensions)
{
string[] Files = System.IO.Directory.GetFiles(FolderPath);
string[] Directories = System.IO.Directory.GetDirectories(FolderPath);
for (int i = 0; i < Directories.Length; i++)
{
LoadFiles(Directories[i], FileExtensions);
}
for (int i = 0; i < Files.Length; i++)
{
for (int j = 0; j < FileExtensions.Length; j++)
{
if (Files[i].ToLower().EndsWith(FileExtensions[j].ToLower()))
{
listBox1.Items.Add(Files[i]);
break;
}
}
}
}
Related
I've been developing a MP3 player in WPF CSharp and when I add a mp3 file, it adds normally, but when I add another mp3 file separately the name of the newly added mp3 file is the same as the first added one here's my code:
private List<String> Files = new List<string> { };
private List<String> Paths = new List<string> { };
private void AddSong_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog() == true)
{
mediaPlayer.Stop();
for (int i = 0; i < ofd.FileNames.Length; i++)
{
Files.Add(System.IO.Path.GetFileNameWithoutExtension(ofd.FileNames[i]));
Paths.Add(ofd.FileNames[i]);
Playlist.Items.Add(Files[i]);
}
}
}
You're adding in Files[i], but i is not the right index to be using there. Instead, add in the most recent file, System.IO.Path.GetFileNameWithoutExtension(ofd.FileNames[i]).
(This is a problem when the Files is not empty when you add extra files, as you observed.)
private List<String> Files = new List<string> { };
private List<String> Paths = new List<string> { };
private void AddSong_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog() == true)
{
int InitialFilesLength = Files.Length;
mediaPlayer.Stop();
for (int i = 0; i < ofd.FileNames.Length; i++)
{
Files.Add(System.IO.Path.GetFileNameWithoutExtension(ofd.FileNames[i]));
Paths.Add(ofd.FileNames[i]);
Playlist.Items.Add(Files[i - InitialFilesLength]);
}
}
}
I'm planning to add this feature on my application where it will display a single line of text on a label which the user imported.
How it works: The user imports a text file, then after a Button click the Label text will change to the first line of text on the text file that the user imported. After X amount of seconds, it will change to the second one. Basically, it will move vertically down until the last line then after it will stop.
List<string> lstIpAddress = new List<string>();
int nCount = 0;
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 30000;
}
private void LoadBTN_Click(object sender, EventArgs e)
{
OpenFileDialog load = new OpenFileDialog();
if (load.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
load.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();
load.Filter = "txt files (*.txt)|*.txt";
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(load.OpenFile()))
{
string line;
while ((line = r.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int nlstItem = 0; nlstItem < lstIpAddress.Count; nlstItem++)
{
listBox1.Items.Add(lstIpAddress[nlstItem]);
}
label2.Text = listBox1.Items[nCount].ToString();
nCount++;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
label2.Text = listBox1.Items[nCount].ToString();
timer1.Start();
}
You need to move nCount++; to a Timer1 click event. Also, you should check if nCount is in range of listBox1.Items.Count otherwise you will get an exception.
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
nCount++;
if (nCount < listBox1.Items.Count)
{
label2.Text = listBox1.Items[nCount].ToString();
}
timer1.Start();
}
Hoping someone can help please?
I can open the Command Prompt from my code but can't work out how to get the files that were search for to delete them via command line. So basically I can search a directory and file extensions which then displays in the listbox. Then i have a button to delete these file (or selected files). I need to help on sending a command to delete the file it has found, eg: del "c:\filepath location\filename.xxx" Hope i am making sense
here is my code:
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Directory.Exists(textBox1.Text))
{
ext = textBox2.Text;
count = 0;
searchDirectory(textBox1.Text);
MessageBox.Show("Total Files: " + count);
}
}
int count = 0;
string ext = "*.*";
private string exeToRun;
private void searchDirectory(string path)
{
try
{
foreach (string file in Directory.GetFiles(path))
{
if (file.EndsWith(ext))
{
count++;
listBox1.Items.Add(file);
}
}
foreach (string directory in Directory.GetDirectories(path))
{
searchDirectory(directory);
}
}
catch (Exception) { }
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
private void button4_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != 1)
{
while (listBox1.SelectedIndex != -1)
{
string filepath = listBox1.Items[listBox1.SelectedIndex].ToString();
if (File.Exists(filepath))
File.Delete(filepath);
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
}
}
private void button5_Click_1(object sender, EventArgs e)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WorkingDirectory = #"C:\";
p.StartInfo.UseShellExecute = false;
p.Start();
}
}
}
Change your command string from
CMD.EXE
to
CMD.EXE /C "DEL C:\MyFile.TXT"
The /C will execute the command string supplied and then terminate the command shell.
Initially I will be loading images(say 20 images) into a picturebox from a specified folder through selection from combobox dropdown, they get loaded normally into the picturebox.
The problem I am facing is when I select the next folder to acquire the image for processing, the previously selected folders images are also displayed in the picturebox after its count only the next folders images are displayed, I am unable to clear the previously loaded images.
To be specific, when I click on a folder from dropdown I want the particular folders image inside the picturebox I don't want the previously loaded images along with them. Am working in VS2013 with c#.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
ArrayList alist = new ArrayList();
int i = 0;
int filelength = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo di = new DirectoryInfo(#"C:\Users\Arun\Desktop\scanned");
DirectoryInfo[] folders = di.GetDirectories();
comboBox1.DataSource = folders;
}
private void button7_Click(object sender, EventArgs e)
{
if (i + 1 < filelength)
{
pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());
i = i + 1;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
private void button8_Click(object sender, EventArgs e)
{
if (i - 1 >= 0)
{
pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = i - 1;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = comboBox1.SelectedItem.ToString();
String fullpath = Path.Combine(#"C:\Users\Arun\Desktop\scanned", selected);
DirectoryInfo di1 = new DirectoryInfo(fullpath);
DirectoryInfo[] folders1 = di1.GetDirectories();
comboBox2.DataSource = folders1;
}
private void button9_Click(object sender, EventArgs e)
{
string selected1 = comboBox1.SelectedItem.ToString();
string selected2 = comboBox2.SelectedItem.ToString();
//Initially load all your image files into the array list when form load first time
System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(Path.Combine(#"C:\Users\Arun\Desktop\scanned", selected1, selected2)); //Source image folder path
try
{
if ((inputDir.Exists))
{
//Get Each files
System.IO.FileInfo file = null;
foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())
{
file = eachfile;
if (file.Extension == ".tif")
{
alist.Add(file.FullName); //Add it in array list
filelength = filelength + 1;
}
else if(file.Extension == ".jpg")
{
alist.Add(file.FullName); //Add it in array list
filelength = filelength + 1;
}
}
pictureBox1.Image = Image.FromFile(alist[0].ToString()); //Display intially first image in picture box as sero index file path
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = 0;
}
}
catch (Exception ex)
{
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.D)
{
if (i + 1 < filelength)
{
pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());
i = i + 1;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
else if(e.KeyCode == Keys.A)
{
if (i - 1 >= 0)
{
pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
i = i - 1;
}
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Your code has many issues.
The one you are looking for is that you don't clear the alist before loading new file names.
So insert:
alist.Clear();
before
//Get Each files
And also
filelength = alist.Count;
after the loop. No need to count while adding!
Also note that ArrayList is pretty much depracated and you should use the type-safe and powerful List<T> instead:
List<string> alist = new List<string>();
Of course a class variable named i is silly and you are also relying on always having a SelectedItem in the comboBox2.
And since you are not properly Disposing of the Image you are leaking GDI resources.
You can use this function for properly loading images:
void loadImage(PictureBox pbox, string file)
{
if (pbox.Image != null)
{
var dummy = pbox.Image;
pbox.Image = null;
dummy.Dispose();
}
if (File.Exists(file)) pbox.Image = Image.FromFile(file);
}
It first creates a reference to the Image, then clears the PictureBox's reference, then uses the reference to Dispose of the Image and finally tries to load the new one.
I have set up a program that so far can browse for the location of a file that possesses data in a text file holding the locations of other files which then shows me if they exist, are missing or are a duplicate inside listboxes. The next step is to enable the user to select files in the checked list boxes and being given the option to either move or copy. I have already made buttons which allow this but I want to be able to use them for the checked boxes I the list boxes.(p.s) please ignore any comments I have made in the code they are just previous attempts of doing other things in the code.
My code so far:
namespace File_existence
{
public partial class fileForm : Form
{
private string _filelistlocation;
public fileForm()
{
InitializeComponent();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void fileForm_Load(object sender, System.EventArgs e)
{
_filelistlocation = textBox1.Text;
}
private void button1_Click(object sender, System.EventArgs e)
{
//GetDuplicates();
checkedListBox1.Items.Clear();
listBox2.Items.Clear();
ReadFromList();
}
private void GetDuplicates()
{
DirectoryInfo directoryToCheck = new DirectoryInfo(#"C:\\temp");
FileInfo[] files = directoryToCheck.GetFiles("*.*", SearchOption.AllDirectories);
var duplicates = files.GroupBy(x => x.Name)
.Where(group => group.Count() > 1)
.Select(group => group.Key);
if (duplicates.Count() > 0)
{
MessageBox.Show("The file exists");
FileStream s2 = new FileStream(_filelistlocation, FileMode.Open, FileAccess.Read, FileShare.Read);
// open _filelistlocation
// foreach line in _filelistlocation
// concatenate pat hand filename
//
}
}
public void ReadFromList()
{
int lineCounter = 0;
int badlineCounter = 0;
using (StreamReader sr = new StreamReader(_filelistlocation))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split('\t');
if (values.Length == 2)
{
string fullpath = string.Concat(values[1], "\\", values[0]);
if (File.Exists(fullpath))
checkedListBox1.Items.Add(fullpath);
else
listBox2.Items.Add(fullpath);
++lineCounter;
}
else
++badlineCounter;
//Console.WriteLine(line);
}
}
}
//StreamReader files= new StreamReader(File)();
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
try
{
string fileName = "filetest1.txt";
string sourcePath = #"C:\Temp\Trade files\removed";
string targetPath = #"C:\Temp\Trade files\queued";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath,fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (IOException exc)
{
MessageBox.Show(exc.Message);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
try
{
string sourceFile = #"C:\Temp\Trade Files\queued\filetest1.txt";
string destinationFile = #"C:\Temp\Trade Files\processed\filetest1.txt";
System.IO.File.Move(sourceFile, destinationFile);
}
catch(IOException ex){
MessageBox.Show(ex.Message);//"File not found"
}
}
private void button4_Click(object sender, System.EventArgs e)
{
OpenFileDialog fileBrowserDlg = new OpenFileDialog();
//folderBrowserDlg.ShowNewFolderButton = true;
//folderBrowserDlg.SelectedPath = _filelistlocation;
fileBrowserDlg.FileName = textBox1.Text;
DialogResult dlgResult = fileBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = fileBrowserDlg.FileName;
File_existence.Properties.Settings.Default.Save();
// Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button5_Click(object sender, System.EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
checkedListBox1.Items.Add(file);
}
}
else
{
checkedListBox1.Items.Add(String.Format("No file found: {0}", textBox1.Text));
}
}
}
}
}
The task I need to do is that the files that appear in the checked list box need to usually be moved or copied to another directory. That is fine as I can already do that with what I have coded, but what it does is it will move or copy all of the files in the checked list box. What I want to do is enable the user to only be able to select which files they what to move or copy through checking the checked list box so that only those files will be moved or copied.
EDIT: Could it be checkedListBox.checked items?