简体   繁体   English

获取没有路径的全名

[英]get fullName without path

I need to enter part of a file name (myTestFiles) And I need to retrieve (myTestFiles_20210305.txt) For now I am recovering (C: \ folder1 \ folder2 \ myTestFiles_20210305.txt)我需要输入文件名的一部分 (myTestFiles) 我需要检索 (myTestFiles_20210305.txt) 现在我正在恢复 (C:\folder1\folder2\myTestFiles_20210305.txt)

For the moment with my order I get the name of the file AND THE PATH, which I do not want.在我的订单中,我得到了我不想要的文件名和路径。

I just want to get the name of the file.我只想获取文件的名称。 and why not the path but on two different exploitable variables.为什么不是路径,而是两个不同的可利用变量。

I am a beginner on this language and on the forums that I have used I only saw what I already had...我是这门语言的初学者,在我使用过的论坛上,我只看到了我已经拥有的东西......

Thank you谢谢

Code:代码:

        string partialName = "myTestFiles";
        DirectoryInfo hdDirectoryInWhichToSearch = new 
        DirectoryInfo(@"C:\Users\Alexandre.boyere\Desktop\test\");

        FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*");

        foreach (FileInfo foundFile in filesInDir)
        {
            string fullName = foundFile.FullName;
            MessageBox.Show(fullName); 
        }

If you want the file name from the path, use Path.GetFileName method:如果您想要路径中的文件名,请使用 Path.GetFileName 方法:

https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-5.0 https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-5.0

Example code from documentation:文档中的示例代码:

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
    path, result);

// This code produces output similar to the following:
//
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext'
// GetFileName('C:\mydir\') returns ''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM