【问题标题】:Get file path and file name from directory - C#从目录获取文件路径和文件名 - C#
【发布时间】:2020-08-13 12:27:15
【问题描述】:

我正在尝试获取我在文件夹中上传的文件的文件路径和文件名。我有这样的路径:

string path = Path.Combine(_webHost.ContentRootPath, "Uploads\\ZipFiles\\");
string extractPath = Path.Combine(_webHost.ContentRootPath, "Uploads\\ExtractedFiles\\");

我将文件上传到path,然后解压缩到extractPath

string fullPath = Path.GetFullPath(extractPath);
string fileName = Path.GetFileName(extractPath);

fullPath 返回正确的路径,但 fileName 为空。我没有得到文件名。 我正在尝试得到这样的东西

var dbfPath = "C://ExtractedFiles//fileName.jpg"; 我打算在一个变量中获取文件路径,在另一个变量中获取文件名,然后将它们连接起来,但我无法获取文件名。最好的方法是什么?

【问题讨论】:

  • 从这一行开始: string fileName = Path.GetFileName(extractPath);获取 extractPath 作为输入,并且不包含文件名,它不能返回文件名:-)
  • extractPath 在您的示例中是目录的路径,而不是文件。如果要获取该目录中的文件名,可以使用 string[] files = Directory.GetFiles(extractPath)
  • extractPath 不包含任何文件名,但包含结束目录名称(extractedfiles)。

标签: c# filenames filepath


【解决方案1】:

要获取 ExtractedFiles 文件夹中的文件:

string[] files = Directory.GetFiles(extractPath)

如果您的 zip 中有文件夹,并且您想递归地获取其中的所有文件,请使用:

string[] files = Directory.GetFiles(extractPath, "*.*", SearchOption.AllDirectories)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-17
    • 2014-07-09
    • 2012-10-04
    • 2011-02-01
    • 2014-06-06
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    相关资源
    最近更新 更多