I am attempting to simply for this bit create a list of the songs within the MyMusic folder and display them in a listbox. The strings will also be used later for voice commands but adding those will not be a problem. My problem is that despite my attempts, I have been unable to remove the path from the displayed name.
InitializeComponent();
string path = #"C:\Users\Toby\Music";
string[] Songs = Directory.GetFiles(path, "*.mp3", SearchOption.TopDirectoryOnly);
List<string> SongList = new List<string>();
int pathlngth = path.Length;
int i = 0;
string fix;
foreach (string Asong in Songs)
{
fix = Asong.Remove(0,pathlngth);
fix = Asong.Remove(Asong.Length-4);
SongList.Add(fix);
i = i + 1;
}
SongList.Add("");
SongList.Add("There are " + i + " songs");
SongBox.Datasource = SongList;
To me at least, this should work. However the results from my Listbox will appear as so:
C:\Users\Toby\Music\Across the line
C:\Users\Toby\Music\Behind Closed Doors
And so on...
Any idea what's wrong? I managed to finally remove the extension. I have tried replacing pathlngth with path.Length to no change at all.
To get FileName from a path
string strSongName = System.IO.Path.GetFileName(FileFullPath);
To get FileNameWithoutExtension from a path
string sFileNameWithOutExtension = Path.GetFileNameWithoutExtension(FileFullPath);
Your Solution:
List<string> SongList = new List<string>();
string path = #"C:\Users\Toby\Music";
string[] Songs = Directory.GetFiles(path, "*.mp3", SearchOption.TopDirectoryOnly);
SongList.Add("");
SongList.Add("There are " + Songs.Length + " songs");
foreach (string Asong in Songs)
{
string sFileNameWithOutExtension = Path.GetFileNameWithoutExtension(Asong);
SongList.Add(sFileNameWithOutExtension);
}
SongBox.DataSource = SongList;
There is an API that already does exactly that - Path.GetFileName
foreach (string song in Songs)
{
SongList.Add(System.IO.Path.GetFileName(song));
}
This will give you the name + extension, if you want to omit the extension you can use Path.GetFileNameWithoutExtension instead.
You are assigning the value of "fix" and then immediately overwriting it.
fix = Asong.Remove(0,pathlngth);
fix = Asong.Remove(Asong.Length-4);
Should probably be
fix = Asong.Remove(0,pathlngth);
fix = fix.Remove(Asong.Length-4);
The other option is to just use Path.GetFileName(Asong); but you'll still need to manipulate it to remove the extension.
If you care for saving the path and just don't want to display it, than any of the previous solutions will be good for you.
If you only care of of the file names than the following will be just for you.
var resultFileNames = Songs.Select(s => Path.GetFileName(s));
This will produce a new list based on Songs but will only store their file names.
Related
I have this method that searches all files and folders in "C:\Sharing".
string[] fileArray = Directory.GetFiles(#"C:\Sharing", "*.*", SearchOption.AllDirectories);
And foreach shows me full path of each file. Great. However, since these are in a directory called "Sharing", I want to check and add files that are like
C:\Sharing\Jerry2022\wedding.jpg (array: 'wedding.jpg', 'Jerry2022')
C:\Sharing\snapshot.jpg (array: 'snapshot.jpg')
C:\Sharing\Newsletter\cover-june.webp (array: 'cover-june.webp', 'Newsletter')
So as you can see, I want to add file and subdirectory name to a string array or List, doesnt matter. Excluding "Sharing".
How can I split the results? I know I can use Substring and LastIndexOf("\") + 1 and separate the ending '' but I'm not sure how to match up the filename with the subdir name too.
Any help is appreciated
You can use DirectoryInfo to get the information you want:
C#:
var directoryInfo = new DirectoryInfo(#"C:\Sharing");
if (directoryInfo.Exists)
{
foreach (var fileInfo in directoryInfo.GetFiles("*.*", SearchOption.AllDirectories))
{
var fileName = fileInfo.Name;
Console.WriteLine(fileName);
var directoryName = fileInfo.DirectoryName;
// you can use split to get the directory name array
Console.WriteLine(directoryName);
}
}
I found an other way, use Uri for this scenario:
C#:
string[] fileArray = Directory.GetFiles(#"C:\Sharing", "*.*", SearchOption.AllDirectories);
foreach (var s in fileArray)
{
var uri = new Uri(s);
var uriSegments = uri.Segments.ToArray();
}
You will see each part of the full path, but you may need to use .Trim('/') for each part. Then you can use string.Equals to get directories which you want.
You could split the results using Split
But of course you can also work with FileInfo instead
I have excel list with file names that I want to move from one folder to another. And I can not just copy paste the files from one folder to another since there are allot of files that do not match the excel list.
private static void CopyPaste()
{
var pstFileFolder = "C:/Users/chnikos/Desktop/Test/";
//var searchPattern = "HelloWorld.docx"+"Test.docx";
string[] test = { "HelloWorld.docx", "Test.docx" };
var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, test.ToString()))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
}
}
I have tried several things but I still think that with a array it would be the easiest way to do it(correct me if I am wrong).
The issue that I face right now is that it can not find any files (there are files under this name.
You can enumerate the files in the directory by using Directory.EnumerateFiles and use a linq expression to check if the file is contained in you string array.
Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d)));
So your foreach would look like
this
foreach (var file in Directory.EnumerateFiles(pstFileFolder).Where (d => test.Contains(Path.GetFileName(d)))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
Actually no, this will not search the directory for pst files. Either build the path yourself using Path.Combine and then iterate over the string-array, or use your approach. With the code above, you need to update the filter, because it will not find any file when given a string[].ToString (). This should do:
Directory.GetFiles (pstFileFolder, "*.pst")
Alternatively, you can iterate over all files without a filter and compare the filenames to your string-array. For this, a List<string> would be a better way. Just iterate over the files like you're doing and then check if the List contains the file via List.Contains.
foreach (var file in Directory.GetFiles (pstFileFolder))
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Here, either iterate over the string array or use a List
if (!nameList.Contains (theFileInfo.Name)) continue;
var destination = soruceFolder + theFileInfo.Name;
File.Move(file, destination);
}
I think you need this
var pstFileFolder = "C:/Users/chnikos/Desktop/Test/";
//var searchPattern = "HelloWorld.docx"+"Test.docx";
string[] test = { "HelloWorld.docx", "Test.docx" };
var soruceFolder = "C:/Users/chnikos/Desktop/CopyTest/";
// Searches the directory for *.pst
foreach (var file in test)
{
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
var source = Path.Combine(soruceFolder, theFileInfo.Name);
var destination = Path.Combine(pstFileFolder, file);
if (File.Exists(source))
File.Move(file, destination);
}
So i got this piece of code
namespace kortspel
{
public partial class Form1 : Form
{
ArrayList kortlek = new ArrayList();
Image c1 = new Bitmap("C:/Users/Mert95/Documents/Visual Studio 2012/Projects/kortspel/Spelkort/c1.png");
And i don't want to add in 50pictures with a unique name such as Image c2 = blablabla.
Some people have said i need to create a loop, to add in these 50pictures, so is there a easier way instead of adding in 50 Images in the array?
You can use Directory.GetFiles(string path, string searchPattern) to get an array of all the files in a directory matching a given pattern.
Then, just iterate over the files in a loop like this:
string path = "C:/Users/Mert95/Documents/Visual Studio 2012/Projects/kortspel/Spelkort/";
string[] files = Directory.GetFiles(path, "*.png");
List<Bitmap> images = new List<Bitmap>();
foreach (var file in files)
{
images.Add(new Bitmap(file);
}
Yes, Linq is a good way.
string path = #"C:\Users\Public\Pictures\Sample Pictures";
string[] files = Directory.GetFiles(path, "*.jpg");
var result = from jpeg in files.AsEnumerable()
select Image.FromFile(jpeg);
In my solution a had a folder with a few files. All this files have the Build Action "Embedded Resource".
With this code I can get a file:
assembly.GetManifestResourceStream(assembly.GetName().Name + ".Folder.File.txt");
But is there any way to get all *.txt files in this folder? A list of names or a method to iterate through them all?
You could check out
assembly.GetManifestResourceNames()
which returns an array of strings of all the resources contained. You could then filter that list to find all your *.txt files stored as embedded resources.
See MSDN docs for GetManifestResourceNames for details.
Try this, returns an array with all .txt files inside Folder directory.
private string[] GetAllTxt()
{
var executingAssembly = Assembly.GetExecutingAssembly();
string folderName = string.Format("{0}.Resources.Folder", executingAssembly.GetName().Name);
return executingAssembly
.GetManifestResourceNames()
.Where(r => r.StartsWith(folderName) && r.EndsWith(".txt"))
//.Select(r => r.Substring(folderName.Length + 1))
.ToArray();
}
NOTE: Uncomment the //.Select(... line in order to get the filename.
have a try with this. here you get all files
string[] embeddedResources = Assembly.GetAssembly(typeof(T)).GetManifestResourceNames();
T is of course your type. so you can use it generic
Just cracked this, use:
Assembly _assembly;
_assembly = Assembly.GetExecutingAssembly();
List<string> filenames = new List<string>();
filenames = _assembly.GetManifestResourceNames().ToList<string>();
List<string> txtFiles = new List<string>();
for (int i = 0; i < filenames.Count(); i++)
{
string[] items = filenames.ToArray();
if (items[i].ToString().EndsWith(".txt"))
{
txtFiles.Add(items[i].ToString());
}
}
I am currently making a piece of software that will allow the user to enter up to 6 directories, each directory is saved as a string (within an array) the loop is then meant to check through the array and any that are not null i.e. actually have a directory assigned are meant to be zipped into their own archive. This is the code I have so far.
private void ZipIt()
{
int nxtFileNum = 0;
string Destination = #"C:\tmpZip" + nxtFileNum + ".zip";
// Check all fields, check if empty, if not save to Selection array
// Seems a inefficient - Possibly loop through Text box control type and collect?
if (String.IsNullOrEmpty(tboxSelect1.Text) == false) { BckupArray[0] = tboxSelect1.Text; };
if (String.IsNullOrEmpty(tboxSelect2.Text) == false) { BckupArray[1] = tboxSelect2.Text; };
if (String.IsNullOrEmpty(tboxSelect3.Text) == false) { BckupArray[2] = tboxSelect3.Text; };
if (String.IsNullOrEmpty(tboxSelect4.Text) == false) { BckupArray[3] = tboxSelect4.Text; };
if (String.IsNullOrEmpty(tboxSelect5.Text) == false) { BckupArray[4] = tboxSelect5.Text; };
if (String.IsNullOrEmpty(tboxSelect6.Text) == false) { BckupArray[5] = tboxSelect6.Text; };
// Create a new ZipFile entity and then loop through each array member, checking if
// it has an assigned value, if so compress it, if not, skip it.
using (ZipFile ZipIt = new ZipFile())
{
nxtFileNum++;
foreach (String q in BckupArray)
{
if (q != null)
{
ZipIt.AddDirectory(q);
ZipIt.Comment = "This archive was created at " + System.DateTime.Now.ToString("G");
ZipIt.Save(Destination);
}
}
}
}
What I am trying to get this to do is save the first user given location to tmpZip0.7z, the second to tmpZip1.7z and so on however at the moment all it is doing is adding each directory to tmpZip0.zip.
Also as a side note, how would I get it to name each archive after the directory selected to be archived?
I am currently using DotNetZip (Ionic.Zip) dll.
I hope I gave enough information guys.
You need to switch some stuff:
foreach (String q in BckupArray)
{
nxtFileNum++;
if (q != null)
{
using (ZipFile ZipIt = new ZipFile())
{
string Destination = #"C:\tmpZip" + nxtFileNum + ".zip";
ZipIt.AddDirectory(q);
ZipIt.Comment = "This archive was created at " +
System.DateTime.Now.ToString("G");
ZipIt.Save(Destination);
}
}
}
Reasons:
The string Destination is fixed after you created it. It doesn't change, just because you increment nxtFileNum.
You created only one ZipFile and you incremented nxtFileNum only once, because the those were outside of your foreach loop
Putting the part that creates the ZipFile into the if makes sure an instance is only created if it is really used.
Well, you can do this with:
var strings = Controls.OfType<TextBox>()
.Select(x => x.Text)
.Where(text => !string.IsNullOrEmpty(text))
.ToList();
using (ZipFile ZipIt = new ZipFile())
{
nxtFileNum++;
string comment = string.Format("This archive was created at {0:G}",
DateTime.Now);
foreach (string directory in strings)
{
ZipIt.AddDirectory(directory);
ZipIt.Comment = comment;
ZipIt.Save(Destination + "." + nxtFileNum);
}
}
That will obviously pull all the textboxes though. An alternative is to have a collection of type List<TextBox> or something similar instead of the six different variables.
Note that that will always create .1, .2, .3 etc even if the user didn't specify the first three names. Let me know if you want to be absolutely faithful to the positioning the user gave.
It's not clear to me that you should really be reusing the same ZipFile object, by the way. I'd expect this to be more appropriate:
string comment = string.Format("This archive was created at {0:G}",
DateTime.Now);
int fileIndex = 0;
foreach (string directory in strings)
{
fileIndex++;
using (ZipFile zipFile = new ZipFile())
{
zipFile.AddDirectory(directory);
zipFile.Comment = comment;
zipFile.Save(Destination + "." + fileIndex);
}
}
(Note how I've renamed the variables to be more conventional, by the way - variables typically start with a lower case letter.)