简体   繁体   English

C#从字符串列表中删除文件扩展名

[英]C# Remove file extension from string list

What my program does is basically it lists file names (including it's extension) from a directory into a listbox. 我的程序基本上是将文件名(包括它的扩展名)从目录列入列表框。 It then has a sorting function which sorts the list strings into alphabetical order. 然后它有一个排序功能,它将列表字符串按字母顺序排序。

Lastly it has a binary search function that allows the users to input any string which the program will then compare and display the matched results into a listbox. 最后它有一个二进制搜索功能,允许用户输入程序将比较的任何字符串,并将匹配的结果显示到列表框中。

Now, all these functions work perfectly however I can't seem to remove the extension off of a file name after a search. 现在,所有这些功能都可以正常工作,但是我似乎无法在搜索后删除文件名的扩展名。

For example in the scanning and sorting part it lists the file names as: filename.mp3 例如,在扫描和排序部分,它将文件名列为:filename.mp3

Now, what I want it do when the searching button is clicked is to remove the file extension and display just the filename. 现在,单击搜索按钮时我想要的是删除文件扩展名并仅显示文件名。

    private void buttonSearch_Click(object sender, RoutedEventArgs e)
    {

        listBox1.Items.Clear();

        string searchString = textBoxSearchPath.Text;


        int index = BinarySearch(list1, 0, list1.Count, searchString);

        for (int n = index; n < list1.Count; n++)
        {
            //Removes file extension from last decimal point ''not working''
            int i = list1[n].LastIndexOf(".");
            if (i > 0)
                list1[n].Substring(0, i);

            // Adds items to list
            if (list1[n].IndexOf(searchString, StringComparison.OrdinalIgnoreCase) != 0) break; 
            listBox1.Items.Add(list1[n]);
        }
        MessageBox.Show("Done");
    }

C#非常简单,如果某些事情需要超过2分钟, 那么框架中可能有一种方法

Try like below ite will help you.... 尝试下面的迭代将帮助你....

Description : Filename without Extension 描述: 没有扩展名的文件名

        listBox1.Items.Add(Path.GetFileNameWithoutExtension(list1[n]));

The Substring method returns a new fresh copy of the string, copied from the source one. Substring方法返回一个新的字符串副本,从源代码复制。 If you want to "cut the extension off", then you must fetch what Substring returns and store it somewhere, ie: 如果你想“切断扩展”,那么你必须获取Substring返回的内容并将其存储在某处,即:

int i = list1[n].LastIndexOf(".");
if (i > 0)
    list1[n] = list1[n].Substring(0, i);

However, this is quite odd way to remove an extension. 但是,删除扩展名是非常奇怪的方法。

Firstly, use of Substring(0,idx) is odd, as there's a Remove(idx) (link) which does exactly that: 首先,使用Substring(0,idx)是奇数,因为有一个Remove(idx) (链接) ,它正是这样做的:

int i = list1[n].LastIndexOf(".");
if (i > 0)
    list1[n] = list1[n].Remove(i);

But, sencondly, there's even better way of doing it: the System.IO.Path class provides you with a set of well written static methods that, for example, remove the extension (edit: this is what L-Three suggested in comments), with full handling of dots and etc: 但是,其次,还有更好的方法: System.IO.Path类为您提供了一组编写良好的静态方法,例如,删除扩展名(编辑:这是L-Three在评论中建议的) ,完全处理点等:

var str = System.IO.Path.GetFileNameWithoutExtension("myfile.txt"); // == "myfile"

See MSDN link 请参阅MSDN链接

It still returns a copy and you still have to store the result somewhere! 它仍然返回一个副本,你仍然必须将结果存储在某个地方!

list1[n] = Path.GetFileNameWithoutExtension( list1[n] );

Use Path.GetFileNameWithoutExtension method. 使用Path.GetFileNameWithoutExtension方法。 Quite easy I guess. 我觉得很容易。

http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension.aspx http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension.aspx

Not sure how you've implemented your directory searching, but you can leverage LINQ to your advantage in these situations for clean, easy to read code: 不确定您是如何实现目录搜索的,但是在这些情况下,您可以利用LINQ来获得干净,易于阅读的代码:

var files = Directory.EnumerateFiles(@"\\PathToFiles")
            .Select(f => Path.GetFileNameWithoutExtension(f));

If you're using .NET 4.0, Enumerate files seems to be a superior choice over GetFiles. 如果您使用的是.NET 4.0,那么Enumerate文件似乎是GetFiles的最佳选择。 However it also sounds like you want to get both the full file path and the file name without extension. 然而,听起来你想要获得完整的文件路径和没有扩展名的文件名。 Here's how you could create a Dictionary so you'd eliminate looping through the collection twice: 以下是如何创建一个Dictionary,以便消除两次循环:

var files = Directory.EnumerateFiles(@"\\PathToFiles")
            .ToDictionary(f => f, n => Path.GetFileNameWithoutExtension(n));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM