从GetFiles返回中删除路径

时间:2014-05-10 20:05:05

标签: c#

我正在尝试简单地为此位创建MyMusic文件夹中的歌曲列表并将其显示在列表框中。这些字符串稍后也将用于语音命令,但添加这些字符串不会有问题。我的问题是,尽管我尝试过,但我无法从显示的名称中删除路径。

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;

至少对我来说,这应该有效。但是,我的列表框的结果将如下所示:

  • C:\ Users \ Toby \ Music \全行
  • C:\ Users \ Toby \ Music \ Behind Closed Doors

依旧...... 知道什么是错的吗?我设法最终删除了扩展名。我试过用path.Length替换pathlngth到没有任何改变。

4 个答案:

答案 0 :(得分:1)

有一个API已经完全正确 - Path.GetFileName

foreach (string song in Songs)
{
    SongList.Add(System.IO.Path.GetFileName(song));
}

这将为您提供名称+扩展名,如果您想省略扩展名,可以使用Path.GetFileNameWithoutExtension代替。

答案 1 :(得分:1)

您正在分配“修复”的值,然后立即覆盖它。

fix = Asong.Remove(0,pathlngth);
fix = Asong.Remove(Asong.Length-4);

应该是

fix = Asong.Remove(0,pathlngth);
fix = fix.Remove(Asong.Length-4);

另一种选择是使用Path.GetFileName(Asong);但你仍然需要操纵它来删除扩展名。

答案 2 :(得分:1)

从路径

获取 FileName
string strSongName = System.IO.Path.GetFileName(FileFullPath);

从路径

获取 FileNameWithoutExtension
string sFileNameWithOutExtension = Path.GetFileNameWithoutExtension(FileFullPath);

您的解决方案:

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;

答案 3 :(得分:0)

如果你想保存路径并且只是不想显示它,那么以前的任何解决方案都会对你有好处。

如果您只关心文件名,那么以下内容将仅适合您。

var resultFileNames = Songs.Select(s => Path.GetFileName(s));

这将生成一个基于歌曲的新列表,但只会存储他们的文件名。