如何从文件名获取文件路径和目录?
所以我有这个filenames.avi的列表。每个来自不同的目录,路径。我有一个列表的txt文件。如何从文件名获取文件路径和目录?
当他们都在同一个文件夹中,这很容易,当我在一个文件夹中的每个文件夹中,我必须相应地更改每个文件的目录路径。
谢谢
您将要使用的System.IO.Path
类。 Path.GetDirectoryName
将返回目录名称(没有尾随'\'字符)。
Path
类还有其他有用的方法,如GetFileName
和GetExtension
。
但那些不工作时,我只有一个文件名,似乎有一个过程之前,搜索每个文件,像@ juann说,任何想法? – TrackmeifYouCan 2013-04-30 09:44:16
Path.GetDirectoryName将返回目录的路径,但只有当你有文件的完整路径或相对路径时,如果你只有文件名,你将不会得到任何东西,Path类基本上只处理提供的字符串,它不会搜索文件系统。 – 2013-04-30 09:44:20
@NikolaDavidovic所以我如何有效地解决这个问题? – TrackmeifYouCan 2013-04-30 09:45:28
这会给你的文件名
fullPath = Path.GetFullPath(file);
fileName = Path.GetFileName(fullPath);
,这会给你的文件路径
shortPath = fullPath.Substring(0, inputText.LastIndexOf("\"));
var sr = new StreamReader("filelist.txt");
while(!sr.EOF)
{
string[] ListFiles = Directory.GetFiles("D:\movies\",
sr.ReadLine()/*your file name is the search pattern*/,
SearchOption.AllDirectories);
if(ListFIles.Count > 0)
{
//File Found
foreach(var f in ListFiles)
{
string fullPath = Path.GetFullPath(file);
string fileName = Path.GetFileName(fullPath);
}
}
}
您可以使用Directory.GetFiles()
方法和搜索子目录。我建议缩小搜索范围,因为访问受限制的文件夹时,你会得到例外,但一般可以使用类似以下将路径返回到文件名的第一次出现还是会回归的方法null
:
public string SearchFileSystem(string filename)
{
string [] files = null;
try
{
files = Directory.GetFiles("C:\\", filename, SearchOption.AllDirectories);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return files==null?null:files.FirstOrDefault();
}
'System.IO.Path.GetFileName(...)' – alex 2013-04-30 09:36:35
我们需要更多的细节。您想做什么?你有什么? .txt文件有什么内容? – nmat 2013-04-30 09:36:39
你认为这可以做到吗?可能有多个文件具有相同的文件名,但在不同的目录中,您打算如何区分它们? – 2013-04-30 09:37:27