C# Visual Studio 文件选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1671127/
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
Visual Studio file selector
提问by kaj
I am new to .NET and the Visual Studio IDE. How to I add to a form a component that lets the user browse the file system to select a certain file which will then allow me to programmatically use the selected path as a string variable?
我是 .NET 和 Visual Studio IDE 的新手。如何向表单添加一个组件,让用户浏览文件系统以选择某个文件,然后允许我以编程方式将所选路径用作字符串变量?
采纳答案by Gregg
OpenFileDialogshould suit your needs. You'll probably need to put a button (or some other clickable type UI element) on the page that will pop the dialog up. Then once the user has selected a file and clicked "OK" you'll just check the response for which file was selected.
OpenFileDialog应该适合您的需要。您可能需要在将弹出对话框的页面上放置一个按钮(或其他一些可点击类型的 UI 元素)。然后,一旦用户选择了一个文件并单击“确定”,您只需检查选择了哪个文件的响应。
回答by harryovers
this should do the trick:
这应该可以解决问题:
string path;
OpenFileDialog file = new OpenFileDialog();
if (file.ShowDialog() == DialogResult.OK)
{
path = file.FileName;
}
the string path should now contain the selected file path
字符串路径现在应该包含选定的文件路径
**Edit: ** As mentioned in a comment below, OpenFileDialog is disposable so should be wrapped in a using statement.
**编辑:** 正如下面的评论中提到的,OpenFileDialog 是一次性的,所以应该包装在 using 语句中。