【问题标题】:How to get file names from the directory, not the entire path如何从目录中获取文件名,而不是整个路径
【发布时间】:2011-10-12 08:51:23
【问题描述】:

我正在使用下面的方法来获取文件名。但它返回整个路径,我不想得到整个路径。我只想要文件名,而不是整个路径。

我怎样才能得到只有文件名而不是整个路径

path= c:\docs\doc\backup-23444444.zip

string[] filenames = Directory.GetFiles(targetdirectory,"backup-*.zip");
foreach (string filename in filenames)
{ }

【问题讨论】:

    标签: c# .net winforms file


    【解决方案1】:

    您可以使用GetFileName 方法仅提取不带路径的文件名:

    string filenameWithoutPath = Path.GetFileName(filename);
    

    【讨论】:

    • 我有很多相同类型的文件如何获取文件名仅包含该文件名的文件列表
    【解决方案2】:

    System.IO.Path 是你的朋友:

    var filenames = from fullFilename
                    in Directory.EnumerateFiles(targetdirectory,"backup-*.zip")
                    select Path.GetFileName(fullFilename);
    
    foreach (string filename in filenames)
    {
        // ...
    }
    

    【讨论】:

    • 我必须在这个地方放什么 fullFilename 我必须给吗
    【解决方案3】:

    试试GetFileName()方法:

    Path.GetFileName(filename);
    

    【讨论】:

      【解决方案4】:
      You can use this, it will give you all file's name without Extension
      
          List<string> lstAllFileName = (from itemFile in dir.GetFiles()
                                                     select Path.GetFileNameWithoutExtension(itemFile.FullName)).Cast<string>().ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-15
        • 1970-01-01
        • 2018-05-31
        • 2012-02-23
        • 1970-01-01
        • 2015-02-01
        • 2012-01-21
        相关资源
        最近更新 更多