从桌面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);

要获得选定文件夹或文件的列表,首先你必须选择你需要的文件夹或文件,这必须使用像FolderBrowserDialog和OpenFileDialog这样的工具。

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

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;
}

最新更新