簡體   English   中英

如何從文件名獲取文件路徑和目錄?

[英]How to get the filepath and directory from a filename?

所以我有這個filenames.avi列表。 每個都來自不同的目錄和路徑。 我有這些列表的txt文件。

當它們都放在同一個文件夾中很容易時,當我將它們都放在一個文件夾中時,我必須相應地更改每個文件的目錄路徑。

謝謝

您將要使用System.IO.Path類。 Path.GetDirectoryName將返回目錄名稱(不帶結尾的“ \\”字符)。

Path類中還有其他有用的方法,例如GetFileNameGetExtension

您可以使用Directory.GetFiles()方法並搜索子目錄。 我建議縮小搜索范圍,因為在訪問受限制的文件夾時您將獲得Exceptions,但是通常可以使用類似於以下方法的方法,該方法將返回文件名首次出現的路徑或返回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();
}

這將為您提供文件名

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);
        }

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM