如何列出目录 C# WPF 中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15104986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:44:25  来源:igfitidea点击:

How to list files in directory C# WPF

c#wpffilelistlistbox

提问by l46kok

I need to get file list without directory name and without file extenstion

我需要获取没有目录名和文件扩展名的文件列表

in

C:\ProgramData\Microsoft\Windows\Start Menu\Programs

C:\ProgramData\Microsoft\Windows\开始菜单\程序

ex)C:\ProgramData\Microsoft\Windows\Start Menu\Programs\7-Zip\7-Zip File Manager.lnk (X)

例如)C:\ProgramData\Microsoft\Windows\Start Menu\Programs\7-Zip\7-Zip File Manager.lnk (X)

7-Zip File Manager (O)

7-Zip 文件管理器 (O)

and list those files in Listbox.

并在列表框中列出这些文件。

I also have to retrive icon and start program if the file name is selected in listbox.

如果在列表框中选择了文件名,我还必须检索图标并启动程序。

Like this.

像这样。

http://www.c-sharpcorner.com/UploadFile/7e39ca/display-start-menu-in-windows-8/Images/Start-Menu-Windows8.jpg

http://www.c-sharpcorner.com/UploadFile/7e39ca/display-start-menu-in-windows-8/Images/Start-Menu-Windows8.jpg

can anybody help me?

有谁能够帮助我?

Thanks.

谢谢。

回答by l46kok

Use Path.GetFileNameWithoutExtensionfor retrieving the file name

使用Path.GetFileNameWithoutExtension检索文件名

string fileName = Path.GetFileNameWithoutExtension("C:\ProgramData\Microsoft\Windows\Start Menu\Programs-Zip-Zip File Manager.lnk);

For listing icons in a listbox, look into WPF ListView Class. You need to define a template in XAML for displaying images:

要在列表框中列出图标,请查看 WPF ListView 类。您需要在 XAML 中定义一个模板来显示图像:

<ListView>
    <ListView.Resources>
        <DataTemplate x:Key="IconTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <Image Grid.Column="0"/>
                <TextBlock Grid.Column="1" Text="{Binding Name}"/>
            </Grid>
        </DataTemplate>
    </ListView.Resources>            
    <ListView.View>     
        <GridView>
            <GridViewColumn CellTemplate="{StaticResource IconTemplate}" Header="Name"/>
            <GridViewColumn DisplayMemberBinding="{Binding FileName}" Header="File Name"/>                   
        </GridView>
    </ListView.View>
</ListView>

To extract the icon from file, you can use ExtractAssociatedIcon from System.Drawingnamespace:

要从文件中提取图标,您可以使用System.Drawing命名空间中的ExtractAssociatedIcon :

Icon icon = Icon.ExtractAssociatedIcon(filePath);