C# 通过从目录中获取文件名添加菜单子项

C# 通过从目录中获取文件名添加菜单子项,c#,winforms,C#,Winforms,代码: 我在源目录中有三个文件,它们似乎显示为菜单子项,但文件名没有显示 有没有办法让文件名“显示”而不是“不可见”?非常感谢你的帮助。谢谢大家! 错过了 private void loadViewTemplates(string path) { foreach (string file in Directory.GetFiles(path, "*.txt")) { ToolStripItem subItem = new ToolStripMenuItem();

代码:

我在源目录中有三个文件,它们似乎显示为菜单子项,但文件名没有显示

有没有办法让文件名“显示”而不是“不可见”?非常感谢你的帮助。谢谢大家!

错过了

private void loadViewTemplates(string path)
{
    foreach (string file in Directory.GetFiles(path, "*.txt"))
    {
        ToolStripItem subItem = new ToolStripMenuItem();
        viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem);
    }
}

因此,代码将是

ToolStripItem.Text - Gets or sets the text that is to be displayed on the item.

我自己找到了一个解决方案,如下所示:

private void loadViewTemplates(string path)  
{  
    foreach (string file in Directory.GetFiles(path, "*.txt"))  
    {  
        ToolStripItem subItem = new ToolStripMenuItem();  
        subItem.Text = Path.GetFileNameWithoutExtension(file);
        viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem);  
    }  
}  

谢谢。

谢谢您的回复。:)但这将返回整个路径“.\..\Folder\filename.txt”作为项目,除非我替换
文件带有
Path.GetFileNameWithoutExtension(文件)。我找到了解决办法。谢谢你的帮助:)我不知道你是否想要所有的文件。当然,Path类包含处理文件名所需的所有方法。嗨,Steve,如果你不介意的话,你能解释一下哪种方法更好吗?答案或我的代码中的一个
viewTemplatesToolStripMenuItem.DropDownItems.Add(Path.GetFileNameWithoutExtension(file))?谢谢您的时间。直接将字符串传递给ToolStripItemCollection意味着框架将为您构建ToolStripItem并将其添加到集合中。但是,我找到了创建ToolStripItem的解决方案,尽管它可能速度较慢,可读性更强。谢谢:)(如果您看到我删除的回复,请忽略,我已将其修复):)
private void loadViewTemplates(string path)  
{  
    foreach (string file in Directory.GetFiles(path, "*.txt"))  
    {  
        ToolStripItem subItem = new ToolStripMenuItem();  
        subItem.Text = Path.GetFileNameWithoutExtension(file);
        viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem);  
    }  
}  
private void loadViewTemplates(string path)
{
    foreach (string file in Directory.GetFiles(path, "*.txt"))
    {
        viewTemplatesToolStripMenuItem.DropDownItems.Add(Path.GetFileNameWithoutExtension(file));
    }
}