C# 如何仅从 SaveFileDialog.FileName 获取目录名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16306/
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
How to get only directory name from SaveFileDialog.FileName
提问by Redbaron
What would be the easiest way to separate the directory name from the file name when dealing with SaveFileDialog.FileName
in C#?
SaveFileDialog.FileName
在 C# 中处理时,将目录名与文件名分开的最简单方法是什么?
采纳答案by Adam Wright
Use:
用:
System.IO.Path.GetDirectoryName(saveDialog.FileName)
(and the corresponding System.IO.Path.GetFileName
). The Path class is really rather useful.
(以及相应的System.IO.Path.GetFileName
)。Path 类确实相当有用。
回答by rjzii
Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String.LastIndexOf; for example:
由于文件名中不允许使用正斜杠,一种简单的方法是使用 String.LastIndexOf; 分割 SaveFileDialog.Filename; 例如:
string filename = dialog.Filename;
string path = filename.Substring(0, filename.LastIndexOf("\"));
string file = filename.Substring(filename.LastIndexOf("\") + 1);
回答by Jay Mooney
The Path object in System.IO
parses it pretty nicely.
中的 Path 对象System.IO
很好地解析了它。
回答by Jake Pearson
You could construct a FileInfo object. It has a Name, FullName, and DirectoryName property.
您可以构造一个 FileInfo 对象。它具有 Name、FullName 和 DirectoryName 属性。
var file = new FileInfo(saveFileDialog.FileName);
Console.WriteLine("File is: " + file.Name);
Console.WriteLine("Directory is: " + file.DirectoryName);