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
Related
New to .net MVC here. I am trying to scan a folder I added to my project labeled MovieMedia and add the name and file path with extension to my existing movie database. Im not sure how to do this. Currently I am adding each one in the seed method this way
new Movies
{
Title = "Jurassic Park",
FilePath = #"~/MovieMedia/Jurassic Park.mp4"
}
or by manually adding the details on a create page.
The goal here is to get the title and path to each movie already in the MovieMedia folder.
You can use below method to get all file list with path, you have to pass directory path as parameter.
public List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
return files;
}
I am using Windows 10 and I have two folders namely Source and Destination. The Destination folder is inside a Dropbox. I have two methods CopySourceFilesToDestination and SynchronizeSourceAndDestination. Fist method copies all folders and files from source to the destination while the second method checks whether the particular filename is present or not in Source folder and if it didn't find the filename in the source it deletes the particular file from the Destination folder. Now I have few files named as below and I don't need to care about the content in the files.
E:\Source\A0000000001\20162356312-Future of Utopia in History. Hayden
White. Historein 7.pdf
E:\Source\T0000000142\20162350775-Étienne Geoffroy Saint-Hilaire,
1772-1844 a visionary naturalist. Hervé Le Guyader.pdf
E:\Source\T0000000403\2016242657-Reveries of the solitary walker;
Botanical writings; and Letter to Franquières. Jean Jacques
Rousseau.pdf
E:\Source\T0000000428\2016243154-Science of Literature- essays on an
incalculable difference.Helmut Müller-Sievers.pdf
When I run my program copies files to the Destination but my SynchronizeSourceAndDestination method deletes all the files expect the first file in the list which doesn't contain any UTF-8 characters.
using System;
using System.IO;
namespace DropboxDemo
{
class Program
{
private static string lookupDirectory = #"E:\Source";
private static string backupDirectory = #"C:\Users\SIMANT\Dropbox \Destination";
static void Main(string[] args)
{
Console.WriteLine("Please wait while copying files.");
CopySourceFilesToDestination(lookupDirectory);
Console.WriteLine("Please wait while synchronizing files.");
SynchronizeSourceAndDestination(backupDirectory);
Console.ReadLine();
}
public static void SynchronizeSourceAndDestination(string dir)
{
foreach (string file in Directory.GetFiles(dir))
{
string destFilePath = file.Replace(backupDirectory, lookupDirectory);
if (!File.Exists(destFilePath))
{
// Delete file from Backup
File.Delete(file);
}
}
foreach (string directory in Directory.GetDirectories(dir))
{
string destinationDirectory = directory.Replace(backupDirectory, lookupDirectory);
if (!Directory.Exists(destinationDirectory))
{
Directory.Delete(directory, true);
continue;
}
SynchronizeSourceAndDestination(directory);
}
}
public static void CopySourceFilesToDestination(string dir)
{
foreach (string file in Directory.GetFiles(dir))
{
string destFilePath = file.Replace(lookupDirectory, backupDirectory);
if (!File.Exists(destFilePath))
{
File.Copy(file, destFilePath);
}
else
{
// Override the existing file
File.Copy(file, destFilePath, true);
}
}
foreach (string directory in Directory.GetDirectories(dir))
{
//Create directory if not present in the destination
string destinationDirectory = directory.Replace(lookupDirectory, backupDirectory);
if (!Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
}
CopySourceFilesToDestination(directory);
}
}
}
}
In the second time, I just copied all files from Destination (which is inside Dropbox) to the Source folder and rerun the program and now it doesn't delete the files. Why am I getting this behaviour? I think when a file is copied to Dropbox, it represents the same file names (what we see from my eyes) in a different way. Could you please help me overcome this issue?
To make my solution workable I changed extended ASCII character by pressing É (Alt + 144), é (Alt + 130). I think it was because the file creator did some copy and paste of the characters directly.
I have some files (.txt, word, excel files) in "C:\ABC\Temp" and I want to move all the .txt files into "C:\ABC\Text", but I'm getting a FileNotFoundException.
Please find attached code.
static void Main()
{
string sp = #"C:/ABC/Temp";
string dp = #"C:/ABC/TextFiles";
string[] fileList=Directory.GetFiles(sp);
foreach(string file in fileList)
{
if (file.EndsWith(".txt"))
{
File.Move(sp,dp);
}
}
}
}
}
You're trying to move the entire directories with File.Move.
You have to specify the file name as well:
File.Move(file, Path.Combine(dp, Path.GetFileName(file)));
So basically i am making an app that will sync file types is different ways, I want to search the whole of a logical Drive for example C:\ for all text files.How ever once i find all the text files i want to apply an action for example move all text files to one location or email all text files to the users email.
I have found this code from a past Stack overflow post
public List<string> Search()
{
var files = new List<string>();
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady))
{
try
{
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories));
}
catch(Exception e)
{
Logger.Log(e.Message); // Log it and move on
}
}
return files;
}
But what i want to know is how do i do somthing when i find the files ?
The code you posted looks like it should fill List<string> files with strings representing names of files that have a .txt extension.
It should be as simple as iterating over the value returned from the function and doing as you please with them.
This code should (untested) check for a target directory, create it if it doesn't exist, and then copy each file returned from Search() to the target path.
List<string> results = Search();
String targetPath = "C:/TargetDirectory/";
if (!System.IO.Directory.Exists(targetPath))
System.IO.Directory.CreateDirectory(targetPath);
foreach (string aFileStr in results)
{
String sourceFile = aFileStr;
String destFile = Path.Combine(targetPath, Path.GetFileName(aFileStr));
System.IO.File.Copy(sourceFile, destFile, true);
}
You would do a foreach on the list of strings that that function returns.
I'm not quite sure if I understand you correctly. If you just want to know how to process your filelist, you could for instance do the following:
var filelist = Search();
foreach (var s in filelist) {
string fn = System.IO.Path.GetFileName(s);
string dest = System.IO.Path.Combine("c:\\tmp", fn);
System.IO.File.Copy(s, dest, true);
}
which will copy all files in filelist to c:\tmp and overwrite files with equal filename.
I have DragDrop enabled in my WinForms application, I'm getting the list of items dropped and storing them in a string array called files, then in the DragDrop event I can do something like:
foreach (string file in files)
{
MessageBox.Show(file);
}
Which would return something like:
C:\Users\MyName\document.txt
Is it possible to get just the file name + extension (e.g. document.txt)? I'm not asking for a complete solution, but could you hint me in that direction?
Use Path static function calls such as:
Path.GetFileName(someFullPath);
See msdn here.
You could also use FileInfo class ..
FileInfo fileInfo = new FileInfo(fileFullPath);
var name = fileInfo.Name;
var extension = fileInfo.Extension;