繁体   English   中英

从桌面获取选定文件 C#

[英]Get selected file from Desktop C#

我想获取桌面上用户选择的文件的文件路径,使用此代码我可以从资源管理器中获取所有文件

public void GetListOfSelectedFilesAndFolderOfWindowsExplorer()
    {
          Shell exShell = new Shell();
            List<string> selected = new List<string>();
            foreach (ShellBrowserWindow window in (IShellWindows)exShell.Windows())
            {
                // check both for either interface to work
                // add an Exit for to just work the first explorer window 
                if ((window.Document as IShellFolderViewDual) != null)
                {
                    foreach (FolderItem fi in window.Document.SelectedItems)
                        selected.Add(fi.Path);
                }
                else if ((window.Document as ShellFolderView) != null)
                {
                    foreach (FolderItem fi in window.Document.SelectedItems)
                        selected.Add(fi.Path);
                }
            }
    }

我需要获取桌面上文件的文件名,但列表结果为空。

选择的文件路径对我来说不清楚,但请尝试使用以下代码获取用户桌面中的文件和文件夹列表

// Get the path of the user's desktop
        string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

        // Get the paths of all files and directories on the desktop
        string[] files = Directory.GetFiles(desktopPath);
        string[] directories = Directory.GetDirectories(desktopPath);

        // Create a string to store the paths
        string message = "";

        // Add all files to the message
        foreach (string file in files)
        {
            message += file + "\n";
        }

        // Add all directories to the message
        foreach (string directory in directories)
        {
            message += directory + "\n";
        }

        // Show the message in a message box
        MessageBox.Show(message, "Paths of files and directories on desktop", MessageBoxButtons.OK, MessageBoxIcon.Information);

要获取所选文件夹或文件的列表,首先您必须 select 您需要的文件夹或文件,这必须使用 FolderBrowserDialog 和 OpenFileDialog 等工具来完成。

下面是一个示例,说明如何使用 OpenFileDialog 允许用户 select 桌面上的多个文件:

DialogResult result = openFileDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            // Get the paths of the selected files
            string[] selectedFiles = openFileDialog1.FileNames;

            // Add all files to the list box
            foreach (string file in selectedFiles)
            {
                message += file + "\n";
            }
        }

对于选择文件夹,您可以使用 FolderBrowserDialog

 DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            // Get the path of the selected directory
            string directory = folderBrowserDialog1.SelectedPath;
            message =  directory;
        }

暂无
暂无

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

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