如何在OpenFileDialog中显示完整路径和文件名
本文关键字:路径 文件名 显示 OpenFileDialog | 更新日期: 2023-09-27 18:25:48
我正在使用openfiledialog打开文件calender.txt,当它打开时,它显示calender为文件名,并在没有目录c:''的过滤器框中显示.txt
有人能告诉我如何对对话框进行编码吗?这样我就可以在对话框中获得C:''calender了
private void openFileButton_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = (@"C:'");
ofd.Filter = ("*.txt| Text File");
ofd.FileName = "calender.txt";
ofd.CheckFileExists = false;
if (ofd.ShowDialog() == DialogResult.OK)
{
if (CheckValidity(ofd.FileName))
{
try
{
streamWriter sw = new streamWriter(ofd.FileName);
}
catch (FileLoadException flEx)
{
MessageBox.Show(flEx.Message);
}
else
{
}
}
}
}
可以在对话框中将文件名设置为您喜欢的任何名称。如果您想在开始时显示完整路径,可以执行以下操作:
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = (@"C:'");
ofd.FileName = Path.Combine(ofd.InitialDirectory, "calendar.txt");
请记住,一旦用户选择了不同的文件,这种情况就不会一直保持下去,但这对你来说并不重要,因为一旦用户选择Open
,FileName
就会为你提供完整的路径。
您可以使用获取用户选择的路径
string path_selected = ofd.FileName;
例如"c:''/users/user/desktop/myfile.txt"
我不知道有什么方法可以返回文件名,但你可以使用字符串方法编辑路径并获得文件名